簡體   English   中英

如何將字符串轉換為ifstream

[英]How to convert a string to a ifstream

我試圖用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。

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

你試過ifstream myfile(path.c_str());

請參閱上一篇關於while (!whatever.eof())問題的帖子

我不確定這實際上是如何編譯的,但我認為你在尋找:

#include <fstream>
#include <string>
//...
//...
std::string filename("somefile.txt");
std::ifstream somefile(filename.c_str());
if (somefile.is_open())
{
    // do something
}
//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);
//---

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM