1、使用 std::getline() 逐行读取
最简单且常用的方法,适用于读取文本文件的每一行。
#include <fstream>
#include <string>
#include <iostream>
int main() {
std::ifstream file("file.txt");
std::string line;
while (std::getline(file, line)) {
// 处理每一行的内容
std::cout << line << std::endl;
}
file.close();
return 0;
}
2、使用 std::istringstream 解析每一行
如需要对每一行的内容进行进一步解析,如提取数字或特定格式的数据,可以结合使用 std::getline()
和 std::istringstream
。
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::ifstream file("file.txt");
std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
int a, b;
if (!(iss >> a >> b)) {
// 处理解析错误
continue;
}
// 处理提取的数字 a 和 b
std::cout << "a: " << a << ", b: " << b << std::endl;
}
file.close();
return 0;
}
3、直接使用 ifstream 提取数据
如果文件中的数据是按空格或其他分隔符分隔的,并且每行的格式一致,可以直接使用 ifstream
提取数据。
#include <fstream>
#include <iostream>
int main() {
std::ifstream file("file.txt");
int a, b;
while (file >> a >> b) {
// 处理提取的数字 a 和 b
std::cout << "a: " << a << ", b: " << b << std::endl;
}
file.close();
return 0;
}
4、逐行处理文本文件内容
C++ 中使用 std::ifstream
按行读取文件是一种非常常见的文件输入操作,特别适用于逐行处理文本文件内容的场景。
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string line;
if (!file.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
while (std::getline(file, line)) {
std::cout << "读取行: " << line << std::endl;
// 可以在这里对每一行进行进一步处理
}
file.close();
return 0;
}