reading input in from a file - c++

so I'm a newbie at C++, and I've been poking around on the internet on how to do this, and so far I have this:
void includeFile(string name){
ifstream ifs;
ifs.open(name);
string commands;
while (getline(ifs,commands)){
commandReader(ifs);
}
ifs.close();
}
(commandReader is a function that takes an istream)
When I try to compile, I get the error "no matching function for call" and then gives me the line number for the ifs.open(name) line. I've included fstream, so not sure why it's doing this

Sorry, never mind; found the answer right after I posted this.
The solution was to have name.c_string() as the parameter instead, as string support was only added in c++11

As #chris pointed out, pre-C++11, ifs.open expects a char*, not an std::string. Try ifs.open(name.c_str()).

Related

Passing a string argument to ifstream

I'm trying to pass a string argument to a function from the main function and then passing this received string argument to ifstream constructor. I'm able to receive this string in the function, but when I pass this argument to ifstream, I get a error message:
no matching function for call to ‘std::basic_ifstream::basic_ifstream(const string&)’
std::ifstream file(fileName);
Here is my code:
int** read_CSV(std::string const& fileName)
{
//cout<<fileName<<"\n";//this works
std::ifstream file(fileName);//problem
//Rest of logic
}
The main function:
int main()
{
int** inputMatrix1 = read_CSV("inputData4_80-20_100x32.csv");
return 0;
}
The variable fileName is creating the problem. If I pass it as it is, it gives the error. But instead, if I explicitly mention the name of the file using string rather than the variable, the code works fine. Can someone explain what exactly is the problem here and how I can solve it?
Okay, so the problem was that I was trying to compile without C++11 standard using just g++ "NameOfFile.cpp". There are 2 possible solutions to the problem, from the comment section, and they are as follows:
Using -std=c++11 when giving the command for compilation. The resultant compilation command would look as follows:
g++ -std=c++11 "NameOfFile.cpp"
Another solution, as pointed out by #Peter, is to use c_str() at the end of the string object, since the ifstream doesn't accept strings as an argument before c++11, so c_str() is used for explicitly converting to a compatible format.
Here's the modified code line for the second solution:
std::ifstream file(fileName.c_str());
Thanks to #Peter and #Holt for their inputs.

C++ - No matching function for call to 'getline'

I cannot figure out the proper syntax for a file istream getline() call
I've tried so many variations of calling getline() with all different kinds of parameters and after looking at several different pieces of documentation and it just won't work.
std::ifstream in("file.txt");
char tmp;
std::getline(tmp, in);
This one results in
../directory/file.cpp:178:2: error: no matching function for call to 'getline'
std::getline(tmp, in);
^~~~~~~~~~~~
But other documentation says
std::ifstream in("file.txt");
char tmp;
in.getline(tmp);
which also spits out
../directory/file.cpp:179:5: error: no matching member function for call to
'getline'
in.getline(tmp);
^~~~~~~~~~~~
All I need to do is read a file line by line and I can't figure it out. Could someone please point me in the right direction? I can provide more information if needed.
getline() reads string, but you pass it a single char.
Use it like this:
std::ifstream in("file.txt");
std::string tmp;
std::getline(in, tmp);

JsonCpp ambiguous overload only in Windows

I need to read a json file with jsoncpp library.
I have this file:
{"one":false,"two":[{"id":"first"},{"id":"second"}],"three":550}
If i need to read only the first id of "two" element, i use:
std::string contents; //Contain the file
Json::Value root;
Json::Reader reader;
reader.parse(contents, root, false);
std::string aux = root["two"][0]["id"].asString();
It works fine in Linux, but when i try it in Windows i have this error:
error: ambiguous overload for 'operator[]' in 'root.Json::Value::operator[](((const char*)"two"))[0]'
Why it happens and how can i fix this? Thanks.
Solved: There are two operator[], one with an int as parameter and other with a const char as parameter, and the compiler doesn't know who to use in Windows, but yes in Linux. Now i use [0u] instead [0] to indicate a number as parameter and it works fine.
This drove me crazy, until I stumbled upon this question, I mysteriously figured it out:
Just cast it to Json::Uint (for some reason), or use 'u':
MapEvent::MapEvent(Json::Value& val)
{
operator_enum = val.get(0u, "").asString();
}

c++: Reading a file line by line

I'm wondering if there's a C++ way of opening a file and reading the input line by line.
I encountered the following code that accomplishes the task:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myfile;
myfile.open ("example.txt");
return 0;
}
I'm encouraged to not use any C functions or commands.
The thing is, my "example.txt" is in the form of a string, and using str.c_str() is a C function, so I guess I have two ways to solve the issue.
Is there another way to read input from a file line by line? Perhaps using something that will accept a string as a parameter for the filepath? Is there a C++ way of doing things? :)
Or, is there another way to convert the string in to a const char *, which is what the myfile.open() function needs?
Many thanks in advance!
EDIT: My lack of practivity and research led me to think c_str() was a C function, and it isn't. My apologies. Since it isn't I have found my answer.
C++11's fstream constructor accepts string. In most cases, you want to use fstream's constructor, rather than .open() - you save one line and one function call.
For reading the file line-by-line, you should use std::getline().
Also note that string::c_str() is still C++ function, not C one, as well as fstream's constructor taking const char *. Most of (if not all, I'm not 100% sure) C standard library function are also included in C++ standard.
Since the issue about str.c_str() is already answered, I'm just gonna add a bit about getting inputs line by line. for example, you wanna take 2 ints input per line, extract them, and put it into a vector.
fstream fs(filename.c_str(), ios_base::in);
string line;
stringstream ss;
int a,b;
vector<int> d;
int numlines;
int i;
for (i = 0; getline(fs, line); i++) {
for (ss.str(line); ss >> a >> b; d.push_back(a), d.push_back(b)) {}
ss.clear();
}
numlines = i;
Hope you get the idea of using getline() and fstream()
It's going to look very similar. You'll want an ifstream instead of an ofstream, you'll want the >> operator, and assuming your file has more than one line, you'll need a loop and the ifstream::feof() function.

Pass path to file / filename as argument to a function that prints the file to screen in C++

As the title says, is there any way to pass the path to the file / filename to open as an argument in the function?
I've written a short code for printing a .txt-file to the screen in C++, but instead of having all the code in the main(), I'd rather have it as an own function that I can call with the filename of the file to open as the only input argument.
Basically the beginning of the function would look like
void printFileToScreen()
{
ifstream fin;
char c;
fin.open("FILE_TO_OPEN.txt", ios::in);
blablabla
}
Now is there any way to pass "FILE_TO_OPEN.txt" when I call the function?
I've tried
void printFileToScreen(string str)
{
ifstream fin;
char c;
fin.open(str, ios::in);
blablabla
}
where I call the function like printFileToScreen("FILENAME.txt"), but with no luck, so I'm not sure how to do this.
Hope anyone can help :)
Unfortunately, the iostream functions deal with const char* types rather than with std::string (the iostream functions were developed independently of the STL). You instead could use std::string::c_str() to obtain a const char*:
fin.open(str.c_str(), ios::in);
As a general design rule, I would not pass the file name to the called function. I would pass the already opened std::istream object to read from. This allows you to do the job of printing in a function, and to do the job of opening the file and dealing with non-existent files in another. This has the bonus of being able to pass std::cin to your function!
Try changing your function to look like this :
void printFileToScreen(const string &str);
//If you pass a const char*, a string will be constructed
or this :
void printFileToScreen(const char *);
The function you wrote expects an instance of std::string to be passed by value.
Never mind, after some more trying and failing I found out that I needed to pass a char pointer, and not a string. :)
Of course you can pass the filename as a function parameter. If in doubt, pass a "const char*" rather than a string. I should work.