首页 > 解决方案 > While 循环接受第一个和第二个 cin 的输入

问题描述

我对这些代码行的意图是创建一个程序,该程序将显示用户键入的短语有多少个字符。我用另外一项任务完成了我的代码行,为用户创建一个提示来结束程序或循环它。为此,我创建了一个 while 循环。一切都很顺利,直到我被提示“再去一次?”。无论我输入什么输入,它都会自动为我提供第一个输入的输出,这意味着它也会为我的第一个 cin 输入输入。作为参考,这是我的代码:

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main()
{
char again = 'y';
string phrase;
while (again == 'y' || again == 'Y')
{

cout << "Enter your phrase to find out how many characters it is: ";
getline(cin,phrase);
cout << phrase.length() << endl;
cout << "Go again? (y/n) " ;

cin >> again;

}
cout << "The end." << endl;

system ("pause");
}

抱歉,如果我的问题含糊不清或使用了错误的术语,我刚刚开始学习 c++。

谢谢。

标签: c++while-loopcin

解决方案


您应该std::cin.ignore()cin>>again.

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main()
{
char again = 'y';
string phrase;
while (again == 'y' || again == 'Y')
{

cout << "Enter your phrase to find out how many characters it is: ";
getline(cin,phrase);
cout << phrase.length() << endl;
cout << "Go again? (y/n) " ;

cin >> again;
cin.ignore();
}
cout << "The end." << endl;

system ("pause");
}

问题是std::cin新行之后仍将保留在输入缓冲区中并getline()会读取该换行符。std::ignore()只会从输入缓冲区中抓取一个字符并将其丢弃。

有关详细信息,请参阅http://www.augustcouncil.com/~tgibson/tutorial/iotips.html#problems


推荐阅读