使用std::getline配合std::ifstream逐行读取文件,循环在文件末尾自动终止,避免使用eof()判断;示例代码展示打开文件、读入vector并打印;推荐reserve预分配空间和关闭同步提升性能,C++17可用string_view减少拷贝。

在C++中读取未知行数的文件,关键在于使用循环逐行读取,直到文件结束。标准库提供了简单而高效的方式实现这一目标,常用的是 std::ifstream 配合 std::getline 函数。
这是最常见也最推荐的方法。无论文件有多少行,都能安全、稳定地读入每一行内容。
示例代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
std::ifstream file("data.txt");
std::string line;
std::vector<std::string> lines;
if (!file.is_open()) {
std::cerr << "无法打开文件!\n";
return -1;
}
while (std::getline(file, line)) {
lines.push_back(line);
}
file.close();
// 打印所有行(可选)
for (const auto& l : lines) {
std::cout << l << '\n';
}
return 0;
}
有些人尝试用 eof() 控制循环,但容易出错。正确的判断应基于 getline 的返回值,因为它在读取失败或到达文件末尾时返回 false。
立即学习“C++免费学习笔记(深入)”;
如果文件较大,可以做一些优化来加快读取速度。
例如:
std::ios::sync_with_stdio(false); std::vector<std::string> lines; lines.reserve(10000); // 若预估有约1万行
以上就是c++++怎么读取未知行数的文件_C++高效读取不定行数文件内容的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号