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

내가 윈도우 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

@ 밥 : 그게 무슨 뜻이야? * 입력 스트림을 사용 중이므로 myfile에 이미 읽으려는 데이터가 있어야합니다. –

+1

누크, 뭐라구? getline을 사용하여 txt 파일의 모든 텍스트를 출력하려고합니다. 전에 ifstream의 이름을 설정하면 제대로 작동하지만 이름을 변경할 수는 없습니다. – bob

4

2010 년 당신이 ifstream myfile(path.c_str());를 시도 VC++입니까?

while (!whatever.eof())에 대한 문제는 previous post을 참조하십시오.

+1

일하고있어! eof()는 다년생 문제입니다. : –

+1

@Fred Nurk : 지금부터는 일주일에 세 번 일년에 한 번씩 만 발생합니다. :-) –

+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); 
//--- 
관련 문제