如何逐行读取文件到字符串类型变量中?

6

我正在尝试使用以下代码按行将文件读取到一个字符串类型的变量中:

#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
注意 James 如何检查流。std::getline 返回流,可以通过 while (file) 这种方式来检查流:这是正确的方法(检查 eof 是不正确的)。参见:http://punchlet.wordpress.com/2009/12/01/hello-world/ - GManNickG
1个回答

11

使用 std::getline

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

5
不,你使用的是istream::read成员函数,你需要使用std::getline函数,它不是一个成员函数。 - James McNellis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接