2010-04-05 64 views
4

我試圖讀取文件裏逐行使用下面的代碼字符串類型變量:如何逐行讀取文件到字符串類型變量?

#include <iostream> 
#include <fstream> 


ifstream file(file_name); 

if (!file) { 
    cout << "unable to open file"; 
    exit(1); 
} 

string line; 
while (!file.eof()) { 
    file.getline(line,256); 
    cout<<line; 
} 
file.close(); 

,當我嘗試使用String類將不能編譯,只有當我使用char file[256]代替。

我該如何逐行獲取字符串類?

+3

注詹姆斯如何檢查流。 'std :: getline'返回流,可以用這種方式檢查流:'while(file)';這是正確的方法。 (檢查'eof'不是。)見:http://punchlet.wordpress.com/2009/12/01/hello-world/ – GManNickG 2010-04-05 23:31:52

回答

10

使用std::getline

std::string s; 
while (std::getline(file, s)) 
{ 
    // ... 
} 
+1

7秒...很好。 :p – GManNickG 2010-04-05 23:29:32

+0

謝謝!我錯過了使用命名空間標準。 – ufk 2010-04-05 23:31:10

+5

@ufk:不,你正在使用'istream :: read'成員函數;你需要使用'std :: getline'函數,它不是一個成員函數。 – 2010-04-05 23:33:02