您好我是C ++的新手,并且我试图理解为什么在使用循环更新数组中的结构时,它会跳过数组下一次迭代的getline以获得更多的扬声器。
#include <iostream>
#include <string>
using namespace std;
struct speaker
{
string speakerName;
string telephone;
string topic;
int fee;
};
int main() {
speaker speakerList[3]; // define array named speakerList with 10 elements of the structure speaker
for (int index = 0; index < 3; index++)
{
//cout << "Index number: " << index << endl;
cout << "Input speaker name: ";
//cin >> speakerList[index].speakerName;
getline (cin,speakerList[index].speakerName);
//cout << "Index number: " << index << endl;
cout << "Input telephone number: ";
cin >> speakerList[index].telephone;
//cout << "Index number: " << index << endl;
cout << "Input speech topic: ";
cin >> speakerList[index].topic;
//cout << "Index number: " << index << endl;
cout << "Input fee: ";
cin >> speakerList[index].fee;
cout << "" << endl;
}
// Array output of struct speaker for elements 0 - 3
// Display all speakers and their data
for (int index = 0; index < 3; index++)
{
cout << "Speaker Name: " << speakerList[index].speakerName << endl;
cout << "Speaker Phone Number: " << speakerList[index].telephone << endl;
cout << "Speaker Topic: " << speakerList[index].topic << endl;
cout << "Speaker Fee: " << speakerList[index].fee << endl;
cout << "" << endl;
}
// change attribute of speaker
// get speaker list so user can select speaker to modify
cout << "Speaker number and name below. " << endl;
for (int index = 0; index < 3; index++)
{
cout << index << ". " << speakerList[index].speakerName << endl;
}
int speakerNum; // declare speaker number variable
cout << "Input number of speaker to update: ";
cin >> speakerNum;
cout << "Update speaker " << speakerNum << " data." << endl;
cout << "" << endl;
cout << "Update speaker name: ";
//cin >> speakerList[speakerNum].speakerName;
getline(cin, speakerList[speakerNum].speakerName);
cout << "Update telephone number: ";
cin >> speakerList[speakerNum].telephone;
cout << "Update speech topic: ";
cin >> speakerList[speakerNum].topic;
cout << "Update fee: ";
cin >> speakerList[speakerNum].fee;
// Display updated speaker results
for (int index = 0; index < 3; index++)
{
cout << "Speaker Name: " << speakerList[index].speakerName << endl;
cout << "Speaker Phone Number: " << speakerList[index].telephone << endl;
cout << "Speaker Topic: " << speakerList[index].topic << endl;
cout << "Speaker Fee: " << speakerList[index].fee << endl;
cout << "" << endl;
}
system("pause");
return 0;
}
在测试getline的用户输入时,第一个循环没有问题。但是当输入下一个扬声器数据时,它会跳过其余循环的speakerName部分。
我在帖子中找到了一些信息:Why getline skips first line?
我不完全理解它,当我输入帖子中提到的命令时:std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
它允许用户输入数据,但无法正确地将其添加到数组中。
任何帮助你都非常感激
谢谢