Как преобразовать строку в ifstream - PullRequest
3 голосов
/ 03 февраля 2011

Я пытаюсь открыть файл с помощью ifstream и хочу использовать строку в качестве пути (моя программа создает путь строки).он скомпилируется, но остается пустым.

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;
   }
}

Я использую Windows 7, мой компилятор VC ++ 2010.

Ответы [ 4 ]

5 голосов
/ 03 февраля 2011
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);
}
4 голосов
/ 03 февраля 2011

Вы пробовали ifstream myfile(path.c_str());?

См. предыдущий пост о проблемах с while (!whatever.eof()).

1 голос
/ 03 февраля 2011

Я не уверен, как это на самом деле компилируется, но я предполагаю, что вы ищете:

#include <fstream>
#include <string>
//...
//...
std::string filename("somefile.txt");
std::ifstream somefile(filename.c_str());
if (somefile.is_open())
{
    // do something
}
0 голосов
/ 16 сентября 2016
//Check out piece of code working for me 
//---------------------------------------
char lBuffer[100];
//---
std::string myfile = "/var/log/mylog.log";
std::ifstream log_file (myfile.str());
//---
log_file.getline(lBuffer,80);
//---
...