流不能正确读取字符串

时间:2018-02-06 22:01:23

标签: c++ input stringstream

我是一名大学生,最近开始使用C ++进行编程,我目前在使用字符串流读取字符串时遇到问题。

我正在从一个.csv文件中读取信息并将信息存储在一个类中,最令我困惑的是我的代码完全适用于我的.csv文件的第一行但不适用于第二行。

这是我的班级:

class Player {
public:
    string name;
    int points = 0;
    int gamesPlayed = 0;
    int todaysPoints = 0;
    int timesPresident = 0;
    int timesScum = 0;
    char playing = 'n';
};

这就是我的.csv文件的格式:

  

Name;Points;Games Played;Times President;Times Scum Grace;0;0;0;0 Gabriel;0;0;0;0

这就是我读它的方式:

int readInPlayersList(Player playersList[], string filename) {
    listIn.open(filename);
    string line;
    istringstream fixedLine;
    int i = 0;
    int j;
    getline(listIn, line); //first line doesn't matter
    while (getline(listIn, line)) {
        if (listIn.eof()) { break; }
        j = 0;
        while (line[j]) {
            if (line[j] == ';') { //swapping ; by space to read in easily
                line[j] = ' ';
            }
            ++j;
        }
        fixedLine.str(line);
        cout << "Before reading, line = " << line << endl;
        fixedLine >> playersList[i].name >> playersList[i].points >> playersList[i].gamesPlayed >> playersList[i].timesPresident >> playersList[i].timesScum;
        cout << "After readng -> " << playersList[i].name << " " <<  playersList[i].points << " " <<  playersList[i].gamesPlayed << " " <<  playersList[i].timesPresident << " " <<  playersList[i].timesScum << endl; //testing output
        ++i;
    }
    return i;
    listIn.close();
}

正如你所看到的,为了找出错误的原因,我在读入类之前输出行中的内容,然后输出类成员,对于第一行,它读取它完全但不是第二个和其他任何其他...请参阅下面的输出:

Output

我真的很想知道我在这里做错了什么,感谢任何帮助,欢呼! 加布里埃尔格罗夫

0 个答案:

没有答案
相关问题