Question

I'm struggling a bit here, I have code that looks similar to this:

#include <iostream>
#include <string>
#include <ifstream>

using namespace std;

int main() {
    string filename;
    cout << "Enter the filename: ";
    cin >> filename;
    ifstream myfile(filename);

    //code that does stuff, eg:
    while (myfile >> thing) {
        mydata[i] = thing;
        i = i + 1; //etc, this *isn't* an issue
    }
}

The main problem is that it doesn't seem to compile with g++ but I'm sure I have this working before. I read somewhere it was the string filename; bit that was broken, but I don't know how else to ask for a file name other than storing it as a string. Can anyone help? Also should I use <fstream> or <ifstream> I don't really see a difference. Thank you.

Was it helpful?

Solution

The first error you need to overcome is this one:

main.cpp:3:20: fatal error: ifstream: No such file or directory
 #include <ifstream>
                    ^
compilation terminated.

Indeed, this header does not exist. You probably meant fstream.

Once that is corrected, the crux of your issue is:

main.cpp: In function 'int main()':
main.cpp:11:29: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'
     ifstream myfile(filename);

This is because fstream constructors, in C++98 and C++03, did not take string arguments. This was a sort of legacy oversight, fixed in C++11.

You have two choices:

  • Switch to C++11 (demo)
  • Pass a C-style string instead (demo)

    ifstream myfile(filename.c_str());
    

In both of the above examples, I've had to remove your entire while loop because it references symbols not declared in your program. When reporting a problem, please take more care, and present a testcase that contains only the problem you're trying to solve.

OTHER TIPS

If you don't have C++11 support, you need to pass a const char* to the ifstream constructor. You can do so like this:

ifstream myfile(filename.c_str());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top