How to read a file line by line to a string type variable?

旧街凉风 提交于 2019-12-07 05:46:26

问题


I'm trying to read a file line by line to a string type variable using the following code:

#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();

it won't compile when I try to use String class, only when I use char file[256] instead.

how can I get line by line into a string class?


回答1:


Use std::getline:

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


来源:https://stackoverflow.com/questions/2581761/how-to-read-a-file-line-by-line-to-a-string-type-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!