2010-04-05 63 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