我正在尝试寻找这个代码片段中的错误。它说了错误: [Error] no match for 'operator>>' in 'inputData >> Player[i].AthleteType::firstName
'for Line:
inputData >> Player[i].firstName;
有人可以告诉我这意味着什么?而且,如果这是从看起来像这样的文件中读取数据的正确方法:
Peter Gab 2653 Kenya 127
Usian Bolt 6534 Jamaica 128
Other Name 2973 Bangladesh -1
Bla Bla 5182 India 129
Some Name 7612 London -1
//this is the structure
struct AthleteType
{
string firstName[SIZE];
string lastName[SIZE];
int athleteNumber[SIZE];
string country[SIZE];
int athleteTime[SIZE];
};
void readInput(int SIZE)
{
AthleteType Player[SIZE];
ifstream inputData("Athlete info.txt");
int noOfRecords=0;
for (int i=0; i < SIZE; i++, noOfRecords++)
{
inputData >> Player[i].firstName;
inputData >> Player[i].lastName;
inputData >> Player[i].athleteNumber;
inputData >> Player[i].country;
inputData >> Player[i].athleteTime;
}
for (int i=0; i < noOfRecords; i++)
{
cout << "First Name: " << Player[i].firstName << endl;
cout << "Last Name: " << Player[i].lastName << endl;
cout << "Athlete Number: " << Player[i].athleteNumber << endl;
cout << "Country: " << Player[i].country << endl;
cout << "Athlete Time: " << Player[i].athleteTime << endl;
cout << endl;
}
}
您的尝试存在几个问题。首先是您的结构
struct AthleteType {
string firstName[SIZE];
string lastName[SIZE];
int athleteNumber[SIZE];
string country[SIZE];
int athleteTime[SIZE];
};
您的编译器错误告诉您,您无法读取一系列字符串,InputData>> firstName [size];。一个字符串一次很好。
如果我凝视着我的水晶球,我会看到您想存储几个运动员。这应该使用向量完成。
vector<Athlete> athletes;
然后可以是
struct Athlete
{
string firstName;
string lastName;
int athleteNumber;
string country;
int athleteTime;
};
每个物体一名运动员。
从输入文件阅读时,您要根据阅读成功阅读。
while(inputData >> athlete){
athletes.push_back(athlete);
}
您可以通过超载operator>> (istream&, Athlete& );
来执行此操作,也可以编写执行类似作业的函数。
istream& readAthlete(istream& in, Athlete& at){
return in >> at.firstName >> at.lastName >> at.athleteNumber >> ... and so on;
}
现在可以将读取功能写为
vector<Athlete> readInput(string filename){
vector<Athlete> athletes;
ifstream inputData(filename);
Athlete athlete;
while(readAthlete(inputData, athlete)){
athletes.push_back(athlete);
}
return athletes;
}
这不是测试的代码,它可能起作用,它可能行不通,但它应该为您提供合理的前进道路。