在我的代码中,“不匹配'运算符>>'”是什么意思?

时间:2016-12-11 11:23:53

标签: c++ arrays file structure

我正试图寻找这段代码中的错误。它表示行的错误:[Error] no match for 'operator>>' in 'inputData >> Player[i].AthleteType::firstName':

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;
    }
}

1 个答案:

答案 0 :(得分:3)

您的尝试有几个问题。首先是你的结构

struct AthleteType {
    string firstName[SIZE];
    string lastName[SIZE];
    int athleteNumber[SIZE];
    string country[SIZE];
    int athleteTime[SIZE]; 
};

您的编译器错误告诉您无法读入字符串数组,inputData&gt;&gt;的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;
}

这不是经过测试的代码,它可能有用,它可能不起作用,但它应该给你一个合理的前进道路。