C++:获取线是用户输入的跳过

C++: getline is beings skipped for user input

本文关键字:输入 用户 获取 C++      更新时间:2023-10-16

getline()的第一个调用被跳过,但第二个调用正在工作。我做错了什么?

string animal, q;
cout << "Darn, I lost. What was is?";
getline(cin, animal);//this is being skipped
cout << "Enter a question that is true for a(n) " << animal << " and false for a(n) " << question->value << ": ";
getline(cin, q);

看起来您在此之前还有其他一些输入。在 getline 之前放置一个 getchar() 以使用缓冲区存储的字符。

 getchar();
 getline(cin, animal);

如果数据像hellon how are you?你用cin来读你好,getlinehow are you?它不起作用。因为 getline 将读取n而不是以下行来解决此问题。可以使用cin.ignore()忽略n,然后使用getline读取以下行。

我想

通了,在我的代码中的其他地方,我使用了标准的"cin"而不是getline(),我想缓冲区中仍然有一些东西,就像@Sourav Kanta说的那样。我想下次我应该使用一个或另一个,而不是两个。