【问题标题】:What does "no match for 'operator >>'" mean in my code?我的代码中“不匹配'运算符>>'”是什么意思?
【发布时间】:2016-12-11 11:23:52
【问题描述】:

我正在尝试查找这段代码中有什么问题。它说错误:[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;
    }
}

【问题讨论】:

  • @StoryTeller JF 正在尝试输入字符串数组。
  • inputData &gt;&gt; Player[i].firstName;不应该是inputData &gt;&gt; Player.firstName[i];吗?除此之外,结构看起来很荒谬。其余代码也是如此。
  • @πάνταῥεῖ 很好 - 这是昨天的char[]! @Jannatul 进展非常迅速。
  • @JackDeeth 我总是很好。告诉别人真相不再被认为是很好了吗?
  • 谢谢@Jack!一旦我弄清楚代码将如何工作,我肯定会这样做:)

标签: c++ arrays file structure


【解决方案1】:

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

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&gt;&gt; (istream&amp;, Athlete&amp; ); 来做到这一点,或者您可以编写一个执行类似工作的函数。

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

这不是经过测试的代码,它可能有效,也可能无效,但它应该为您提供合理的前进道路。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2015-09-18
    • 2017-03-29
    • 2011-03-16
    • 2011-07-09
    • 2016-07-23
    相关资源
    最近更新 更多