首页 > 解决方案 > 通过 cin.getline 函数输入一行时命令意外中止

问题描述

通过 cin.getline 函数输入一行时命令意外中止

3
曼联
2
罗纳尔多 葡萄牙
鲁尼 英格兰
埃弗顿
2
鲁尼 英格兰
巴克利 英格兰
皇家马德里
3
菲戈 葡萄牙
罗纳尔多 葡萄牙
贝尔 威尔士
葡萄牙

输出:
曼联
皇家马德里

using namespace std;

struct footballer {
    string footballer_name;
    char* country = new char;
};

struct club {
    char* club_name = new char[10001];
    int footballersCount;
    footballer* footballers;
};


int main(){
    int number_of_clubs;
    cin >> number_of_clubs;
    struct club struct_club[1001];
    struct footballer struct_footballer[100][100];
    for (int i = 0; i < number_of_clubs; i++) {
        cin.getline(struct_club[i].club_name, 256);
        cin >> struct_club[i].footballersCount;
        for (int j = 0; j < struct_club[i].footballersCount; j++) {
            cin >> struct_footballer[i][j].footballer_name >> struct_footballer[i][j].country;
        }
    }
    for (int i = 0; i < number_of_clubs; i++) {
        cout << struct_club[i].club_name << endl;
        cout << struct_club[i].footballersCount << endl;
        for (int j = 0; j < struct_club[i].footballersCount; j++) {
            cout << struct_footballer[i][j].footballer_name << " " << struct_footballer[i][j].country << endl;
        }
    }
}

标签: c++inputstructgetline

解决方案


那是因为每次在 cin>> 之后使用 cin.getline() 都必须使用 cin.ignore() 因为 cin>> 将新行 ch 留在缓冲区中。只需添加 cin.ignore(); 作为您进入第一个循环时的第一行。


推荐阅读