我正在尝试使用以下代码按行将文件读取到一个字符串类型的变量中:
#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