c++ - 通过 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;
}
}
}
解决方案
那是因为每次在 cin>> 之后使用 cin.getline() 都必须使用 cin.ignore() 因为 cin>> 将新行 ch 留在缓冲区中。只需添加 cin.ignore(); 作为您进入第一个循环时的第一行。
推荐阅读
- python - 将带有参数的命令传递给 subprocess.Popen
- java - 如何使用递归方法返回字符串中的数字总和?
- vb.net - 当我使用 vb.net 在 youtube 中搜索时,如何播放获得的第一个 url?
- hp-idol-ondemand - 位于连接数据库中的索引特定条目 [IDOL 索引服务器]
- ionic-framework - Ionic 3/4 - 每日本地通知不起作用
- javascript - 文件加载器将图像保存到每个文件夹,例如 Project/Module/src/img/example.jpg 到 Project/Module/dist/img/example.jpg
- reactjs - 使用 Firebase 数据设置状态后,React 渲染未更新
- php - 防止将空字符串保存到数据库
- javascript - 在选择日期选择器值上动态显示 Morrise.js 悬停标签
- python - 从数组值中过滤字典