Austin Henley
Austin Henley

Reputation: 4633

ifstream error with g++ but compiles with Visual Studio

I have been using Visual Studio for a project I am working on, though it must also compile with GCC on Linux. I have completed my project and it runs fine, but I sent the files over to my Linux shell and I receiving an error with a trivial line of code:

std::ifstream input(s);

This gives me error saying there is no matching function. s is an std::string by the way. Can anyone enlighten me why this runs under Visual Studio but not GCC, even though I am looking at the documentation for ifstream? Perhaps an old version of GCC?

EDIT: GCC version is 4.2.1 The exact error is:

error: no matching function for call to 'std::basic_ifstream<char,  
std::char_traits<char>>::basic_ifstream(std::string&)'

EDIT 2: Relevant code:

std::string s = "";
if(argc == 2)
    s = argv[1];
else{
    std::cout << "Bad filename?" << std::endl;
    return 1;
}
std::ifstream input(s);

Upvotes: 3

Views: 3516

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

Download latest version of GCC, and compile your program with -std=c++0x option. In C++11, stream classes has constructor which takes std::string as argument, and GCC by default doesn't enable C++11, so you need to enable by providing -std=c++0x compiler option.

If you cannot use C++11, then do this:

std::ifstream input(s.c_str());

This should compile, both in C++03 and C++11.

Upvotes: 7

Related Questions