首先用ifstream读取文件每行,再通过stringstream解析每行数据。例如读取包含姓名、年龄、成绩的文本文件,利用stringstream提取各字段并转换类型,实现数据分离与处理。

在C++中,结合
stringstream
ifstream
stringstream
当你有一个文本文件,每行包含多个由空格或分隔符分开的数据时,可以先读取整行,再用
stringstream
例如,假设文件
data.txt
你可以这样读取并解析:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ifstream file("data.txt");
if (!file.is_open()) {
cerr
return 1;
}
string line;
while (getline(file, line)) {
if (line.empty()) continue; // 跳过空行
// 将每行内容放入 stringstream
stringstream ss(line);
string name;
int age;
double score;
// 从 stringstream 中提取数据
if (ss >> name >> age >> score) {
cout
} else {
cerr
}
}
file.close();
return 0;
}
stringstream
operator>>
比如,你想确保年龄字段是整数:
ss >> age
这种机制比直接使用
stoi()
stringstream
如果文件使用逗号分隔(CSV),可以在读取字段时手动跳过分隔符。
例如,处理
Tom,28,78.5
stringstream ss(line);
string name; int age; double score;
char comma;
if (ss >> name >> comma
>> age >> comma
>> score) {
cout
}
注意:名字含空格时需用
getline(ss, name, ',')
你也可以用
stringstream
例如,处理完数据后生成报告:
stringstream output;
output
ofstream out("result.txt");
out
out.close();
基本上就这些。关键是把文件读取和字符串解析分开处理,
stringstream
以上就是C++如何结合字符串流stringstream处理文件内容的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号