4

What type must I make my file name to use it as an argument to ifstream.open()?

int main(int argc, char *argv[]) {
    string x,y,file;

    string file = argv[1];
    ifstream in;
    in.open(file);
    in >> x;
    in >> y;
    ...

With this code, I get the following error:

main.cpp|20|error: no matching function for call to 'std::basic_ifstream<char,
     std::char_traits<char> >::open(std::string&)'|
gcc\mingw32\4.4.1\include\c++\fstream|525|note: candidates are: void std::basic_ifstream<_CharT,
     _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]|

UPDATE:

i get this error enter image description here

Jaanus
  • 16,161
  • 49
  • 147
  • 202
  • now you updated the question with a completely different problem. try running the program with the debugger and see where it crashes – Marius Bancila Mar 10 '11 at 06:52

1 Answers1

8

The constructor takes a const char* (http://www.cplusplus.com/reference/iostream/ifstream/ifstream/) so you should do it like this:

in.open(argv[1]);

or if you really want to use the file string variable, then

in.open(file.c_str());
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • 1
    Also, if you use a slightly newer compiler, it will have an overload for std::string as well. Required by C++0x. – Bo Persson Mar 09 '11 at 20:48
  • 1
    @Bo: wow, wait, what? C++ is finally going to support its `string` class? – rubenvb Mar 09 '11 at 20:56
  • @rubenvb: Yeah, that's the advantage of a revised standard! :-) Historically, the stream classes were designed long before there was a string class, so they couldn't support one. And nobody thought of going back and fix that. Until now! – Bo Persson Mar 09 '11 at 21:01
  • weird i tried using the `in.open(argv[1]);`, it compiles but it crashes the console. – Jaanus Mar 09 '11 at 21:15
  • Or, if you have an older compiler and boost ... `boost::filesystem::ifstream in; in.open(file);` – Robᵩ Mar 09 '11 at 21:17
  • @Maris Bancila, @Rob Adams, @Bo Persson, @Hans Passant .. well i updated first post, the program compiles now, but the command window crashes – Jaanus Mar 09 '11 at 22:38