找不到我的错误。程序不会忽略问题并与 while 语句交火



程序不忽略字符串问题并干扰while语句。当我回答第一个问题时,我不能回答"你想再问一个问题吗?"回答Y/N:"因为节目结束了。我已经放进去了。忽略,所以我不知道为什么它不忽略第一个问题的答案

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int rollDie();
int main()
{
string question;
char repeat;

do
{
cout << "Hello, I am the magic 8-ball! Ask me a question and I will give you an answer" << endl;
cout << "Your question: ";

cin >> question;
cin.ignore();
cout << endl << endl;

int roll = rollDie() % 5 + 1;
if (roll == 5)
cout << "Answer: It is certain " << endl;
if (roll == 4)
cout << "Answer: Reply hazy, Try Again " << endl;
if (roll == 3)
cout << "Answer: Don't count on it " << endl;
if (roll == 2)
cout << "Answer: Signs point to yes " << endl;
if (roll == 1)
cout << "Answer: My sources say no " << endl;

cout << "Would you like to ask another question? Answer Y/N: ";
cin >> repeat;
} while (repeat == 'Y' || repeat == 'y');


cout << endl << endl;
system("pause");
return 0;
}

int rollDie()
{
srand(time(NULL));
return rand();
}

不要使用cin >> question。这将只读取到下一个空格。如果超出了这个范围,其他cin语句将读取它们。相反,使用std::getline():

std::getline(std::cin, question);

相关内容

  • 没有找到相关文章