开发者

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

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 g开发者_StackOverflow社区et line by line into a string class?


Use std::getline:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜