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

ufk*_*ufk 5 c++ fstream iostream

我正在尝试使用以下代码逐行读取文件到字符串类型变量:

#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();
Run Code Online (Sandbox Code Playgroud)

当我尝试使用String类时,它不会编译,只有在我使用时才会编译char file[256].

如何逐行进入字符串类?

Jam*_*lis 11

用途std::getline:

std::string s;
while (std::getline(file, s))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • @ufk:不,你正在使用`istream :: read`成员函数; 你需要使用`std :: getline`函数,它不是一个成员函数. (5认同)