如何逐行读取文件到字符串类型变量?
问题描述:
我试图读取文件里逐行使用下面的代码字符串类型变量:如何逐行读取文件到字符串类型变量?
#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]
代替。
我该如何逐行获取字符串类?
注詹姆斯如何检查流。 'std :: getline'返回流,可以用这种方式检查流:'while(file)';这是正确的方法。 (检查'eof'不是。)见:http://punchlet.wordpress.com/2009/12/01/hello-world/ – GManNickG 2010-04-05 23:31:52