Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a ifstream

Tags:

c++

ifstream

i am trying to open a file with ifstream and i want to use a string as the path (my program makes a string path). it will compile but it stays blank.

string path = NameOfTheFile; // it would be something close to "c:\file\textfile.txt"
string line;

ifstream myfile (path); // will compile but wont do anything.
// ifstream myfile ("c:\\file\\textfile.txt"); // This works but i can't change it
if (myfile.is_open())
{
   while (! myfile.eof() )
   {
      getline (myfile,line);
      cout << line << endl;
   }
}

I am using windows 7, My compiler is VC++ 2010.

like image 447
bob Avatar asked Dec 12 '22 16:12

bob


1 Answers

string path = compute_file_path();
ifstream myfile (path.c_str());
if (!myfile) {
  // open failed, handle that
}
else for (string line; getline(myfile, line);) {
  use(line);
}
like image 107
Fred Nurk Avatar answered Dec 29 '22 08:12

Fred Nurk