我编写这些代码行的目的是创建一个程序来显示用户键入的短语有多少个字符。我用另一个任务完成了我的代码行,为用户创建一个提示来结束程序或循环它。为此,我创建了一个 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++。
谢谢。
最佳答案
您应该在 cin>> 之后再次添加
。std::cin.ignore()
#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
关于c++ - while 循环接受第一个和第二个 cin 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55259527/