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

2024-02-19

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

#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]反而。

如何逐行进入字符串类?


Use std::getline:

std::string s;
while (std::getline(file, s))
{
    // ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐