第1个回答 2010-08-30
以下代码在visual studio2008下测试成功,另外,给楼主一个建议:为了能更方便地操作数据,建议别把数据存在两个数组中。由于你的第一列是序号,具有唯一性,因此可以将它们存在一个map中。代码如下:
//////////////////////////////////////////////////////////////////////////
//
// 说明:为了能更方便地操作数据,我建议别把数据存在两个数组中。由于你的第一
// 列是序号,具有唯一性,因此可以将它们存在一个map中
#include <fstream>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <map>
using namespace std;
int main()
{
std::ifstream in("transaction.txt");
if (!in) { cerr << "打开文件transaction.txt读取数据错误" << endl; return 1; }
typedef vector<int> IntVec;
map<int, IntVec> iIntVecMap; // 记录信息,每条记录对应文件中的一行
string szRcdInfo;
char buffer[500]; // 根据行数据的最大个数调整数据的大小
int iXuhao;
while (in.getline(buffer, 500))
{
szRcdInfo = buffer;
int index = szRcdInfo.find(" "); // 查找空格,以便读取序号列
if (index == -1) { cerr << "数据格式错误" << endl; return 1; }
iXuhao = atoi(szRcdInfo.substr(0, index).c_str()); // 读取序号
int index2;
IntVec intVec;
while(index != -1) // 读取其对应的数据
{
int iData = 0;
index2 = szRcdInfo.find(',', index+1);
if (index2 != -1)
iData = atoi(szRcdInfo.substr(index+1, index2-index).c_str());
else
iData = atoi(szRcdInfo.substr(index+1, szRcdInfo.length()-index).c_str());
intVec.push_back(iData);
index = index2;
}
iIntVecMap[iXuhao] = intVec; // 插入到信息记录中
}
// 输出,观察是否正确. 已测试成功
for (map<int, IntVec>::iterator mapIt = iIntVecMap.begin(); mapIt != iIntVecMap.end(); ++mapIt)
{
cout << mapIt->first << " ";
IntVec &intVec = mapIt->second;
for (IntVec::iterator vecIt = intVec.begin(); vecIt != intVec.end(); ++vecIt)
{
cout << ", " << *vecIt;
}
cout << endl;
}
return 0;
}
在我电脑上的测试结果:
1 , 77, 310, 533, 1392
2 , 154, 360, 1196, 1242
3 , 181, 963, 1306, 1383
4 , 337, 1512
5 , 483
6 , 327, 377, 653, 942
7 , 218, 927, 1449, 1493
8 , 826, 886, 1003
9 , 726, 1302, 1545
10 , 603, 623, 959
11 , 281, 763
12 , 243, 809, 1091, 1231
13 , 379, 1055, 1211
14 , 79, 375, 1017, 1155, 1177, 1221, 1437
第3个回答 2010-08-30
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void main(){
char ch[100] = "\0";
char a[100][100],b[100][100];
int x=0,y=0;
ifstream fin("transaction.txt",ios::in);
fin.getline(ch,100);
while(!fin.eof()){
cout<<ch<<endl;
char *result = NULL;
result = strtok(ch," ");
strcpy(a[x++],result);
cout<<a[x-1]<<endl;
result = strtok(NULL,",");
while( result != NULL ) {
strcpy(b[y++],result);
cout<<b[y-1]<<endl;
result = strtok( NULL, "," );
}
memset(ch,0,100);
fin.getline(ch,100);
}
fin.close();
/* for(int i=0;i<14;i++)
{
cout<<"a "<<a[i]<<" b "<<b[i]<<endl;
}*/
}
//已运行过了,没问题