2011-02-02 30 views
2

我想用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

回答

4
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); 
} 
+1

這似乎並不工作,同樣的事情發生。我得到的只是一個空白的myfile。 – bob 2011-02-02 23:44:41

+1

@bob:你是什麼意思?您正在使用*輸入*流,所以myfile必須已經包含要讀取的數據。 – 2011-02-02 23:46:12

+1

nurk,什麼?我正在嘗試使用getline將所有文本輸出到txt文件中。它工作正常,如果我以前設置ifstream的名稱,但然後我不能更改名稱。 – bob 2011-02-02 23:49:45

4

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

查看previous post關於while (!whatever.eof())的問題。

1

我不確定這實際上是如何編譯,但我相信你正在尋找:

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