以下代码 VS2010 编译通过,运行结果正常
关键运用:std::fstream 标准库对象;std::stringstring 标准库对象
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
int main()
{
char *path = "S:/1.txt"; // 这里填写你的文件路径,用‘/’或者‘\\’
std::ifstream ifile(path); // 打开文件
std::string line; // 用于存放从文件读取的每一行
int arr1[5], arr2[5]; // 分别存放读取到的 1,2,3,4,5 和 2,3,4,5,6
if (ifile) // 检查文件是否打开成功
{
char comma; // 用于过滤掉 1,2,3,4,5 中的‘,’
std::string pfx; // 用于过滤掉每行前面的字符串
getline(ifile, line); // 读取文件第一行
std::istringstream instr1(line); // 将第一行绑定给 istringstream 对象
instr1 >> pfx; // 过滤第一行前面的字符串
for (int x = 0; x != 4; ++x)
{
instr1 >> arr1[x] >> comma;
}
instr1 >> arr1[4]; // 读取数据存入数组,并过滤掉‘,’
getline(ifile, line); // 第二行读取开始,步骤同上
std::istringstream instr2(line);
instr2 >> pfx;
for (int x = 0; x != 4; ++x)
{
instr2 >> arr2[x] >> comma;
}
instr2 >> arr2[4];
}
else
{
std::cout << "打开文件错误!" << std::endl;
return EXIT_FAILURE;
}
// 下面是显示读取结果
for (int x = 0; x != 5; ++x)
{
std::cout << arr1[x] << " ";
}
std::cout << std::endl;
for (int x = 0; x != 5; ++x)
{
std::cout << arr2[x] << " ";
}
std::cout << std::endl;
return 0;
}
=========
运行结果:
1 2 3 4 5
2 3 4 5 6
Press any key to continue . . .
温馨提示:答案为网友推荐,仅供参考