C++读取文件中有逗号的数据

来源:互联网 发布:炫舞房间源码 编辑:程序博客网 时间:2024/05/29 03:26
用C++读取目录下的123.txt文件内容,文件内容为:
023,456,789,012,345,678
234,567,890,123,456,789
345,678,901,234,567,890

每行数据用逗号分隔,分别读取,然后输出,代码:

#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;


int main()
{
ifstream inf;
inf.open("123.txt", ifstream::in);


const int cnt = 6;          


string line;

int i = 0;
        int j = 0;
size_t comma = 0;
size_t comma2 = 0;



while (!inf.eof())
{
getline(inf,line);


comma = line.find(',',0);
i = atoi(line.substr(0,comma).c_str());
cout<<i<<' ';
while (comma < line.size() && j != cnt-1)
{
comma2 = line.find(',',comma + 1);
i = atoi(line.substr(comma + 1,comma2-comma-1).c_str());
cout<<i<<' ';
++j;
comma = comma2;
}
cout<<endl;
j = 0;
}


inf.close();


return 0;


输出结果:

23 456 789 12 345 678
234 567 890 123 456 789
345 678 901 234 567 890


0 0
原创粉丝点击