2011-02-02 3 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を使用しています、私のコンパイラは

答えて

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

+1

@bob:それはどういう意味ですか? *入力*ストリームを使用しているため、myfileにはすでに読み込みたいデータが含まれている必要があります。 –

+1

ナルク、何?私はgetl​​ineを使ってtxtファイルのテキストをすべて出力しようとしています。前にifstreamの名前を設定するとうまく動作しますが、名前を変更できません。 – bob

4

2010年はあなたがifstream myfile(path.c_str());を試してみましたVC++のですか?

while (!whatever.eof())の問題については、previous postを参照してください。

+1

で働いていると思います!eof()は多年生問題です。 : –

+1

@Fred Nurk:今から週に3回ではなく、1年に1回しか発生しないのでしょうか?:-) –

+1

はい、私はそれを試みました。 – bob

1

は、私は、これは実際にコンパイルする方法などがわからないんだけど、私はあなたが探していると仮定します。これは、動作していないよう

#include <fstream> 
#include <string> 
//... 
//... 
std::string filename("somefile.txt"); 
std::ifstream somefile(filename.c_str()); 
if (somefile.is_open()) 
{ 
    // do something 
} 
+0

somefileは空白です。 – bob

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); 
//--- 
関連する問題