c++如何读取包含多列不同类型数据的txt文件
txt文件格式如下:score1 11.2 score2 10.1
score3 11.2 score4 10.1
score5 11.2 score6 10.1
... ....
就是字符串 空格 数字的形式,总行数不定。
想要实现的是读入txt中的各列数字到数组中,并进行排序。
只是不知道怎么读
用ifstream + getline只能把每行读成一个字符串,不能直接读到数组中
这个有没有比较成熟的方法?
程序代码:#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
int main( void )
{
// 打开文件
ifstream fin( "d:\\a.txt" );
if( !fin )
return 1;
vector<double> sb, sd;
{
// 读入数据
string a, c;
for( double b,d; fin>>a>>b>>c>>d; )
{
sb.push_back(b);
sd.push_back(d);
}
// 排序
sort( sb.begin(), sb.end() );
sort( sd.begin(), sd.end() );
}
// 输出
cout << "array1 = ";
copy( sb.begin(), sb.end(), ostream_iterator<double>(cout," ") );
cout << '\n';
cout << "array2 = ";
copy( sd.begin(), sd.end(), ostream_iterator<double>(cout," ") );
cout << '\n';
return 0;
}
程序代码:#include <iostream>
#include <fstream>
#include <vector>
#include <limits>
#include <algorithm>
#include <iterator>
using namespace std;
int main( void )
{
// 打开文件
ifstream fin( "d:\\a.txt" );
if( !fin )
return 1;
// 读入数据
vector<double> sb, sd;
{
for( double b,d; ((fin>>ws).ignore(numeric_limits<streamsize>::max(),' ')>>ws>>b>>ws).ignore(numeric_limits<streamsize>::max(),' ')>>d; )
{
sb.push_back(b);
sd.push_back(d);
}
// 排序
sort( sb.begin(), sb.end() );
sort( sd.begin(), sd.end() );
}
// 输出
cout << "array1 = ";
copy( sb.begin(), sb.end(), ostream_iterator<double>(cout," ") );
cout << '\n';
cout << "array2 = ";
copy( sd.begin(), sd.end(), ostream_iterator<double>(cout," ") );
cout << '\n';
return 0;
}