【问题标题】:How to read a file line by line to a string type variable?如何逐行读取文件到字符串类型变量?
【发布时间】: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] 时。

如何逐行获取字符串类?

【问题讨论】:

标签: c++ iostream fstream


【解决方案1】:

使用std::getline:

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

【讨论】:

  • @ufk:不,你使用的是istream::read成员函数;你需要使用std::getline函数,它不是成员函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
相关资源
最近更新 更多