【发布时间】:2010-04-05 23:26:55
【问题描述】:
我正在尝试使用以下代码逐行读取文件到字符串类型变量:
#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] 时。
如何逐行获取字符串类?
【问题讨论】:
-
请注意 James 如何检查流。
std::getline返回流,可以通过这种方式检查流:while (file);这是正确的方法。 (检查eof不是。)请参阅:punchlet.wordpress.com/2009/12/01/hello-world