【发布时间】:2020-06-07 01:28:17
【问题描述】:
我正在尝试创建一个小型餐厅程序,我将在其中练习我目前在 C++ 中学到的所有内容。但是我跳进了一个小问题。在程序开始时,我会提示用户是否要进入程序,或者选择Y或N退出程序。如果输入的不是其他任何内容,程序会告诉用户无效。
问题是假设用户输入了一个无效字符 a。 无效的输出将正常显示,一切看起来都很完美。 但如果用户输入两个或更多字符,则无效输出大小写将与用户输入的字符一样多。示例如下:
#include <iostream>
int main()
{
char ContinueAnswer;
std::string Employee {"Lara"};
std::cout << "\n\t\t\t---------------------------------------"
<< "\n\t\t\t| |"
<< "\n\t\t\t| Welcome to OP |"
<< "\n\t\t\t|Home to the best fast food in Orlando|"
<< "\n\t\t\t| |"
<< "\n\t\t\t--------------------------------------|" << std::endl;
do
{
std::cout << "\n\t\t\t Would you like to enter? (Y/N)"
<< "\n\t\t\t "; std::cin >> ContinueAnswer;
if(ContinueAnswer == 'y' || ContinueAnswer == 'Y')
{
system("cls");
std::cout << "\n\t\t\t My name is " << Employee << "."
<< "\n\t\t\tI will assist you as we go through the menu." << std::endl;
}
else if(ContinueAnswer == 'n' || ContinueAnswer == 'N')
{
std::cout << "\t\t\t\tGoodbye and come again!" << std::endl;
return 0;
}
else
std::cout << "\n\t\t\t\t Invalid Response" << std::endl;
}
while(ContinueAnswer != 'y' && ContinueAnswer != 'Y')
感谢您花时间阅读并感谢任何回答的人:)
【问题讨论】:
-
在
do-while循环的每次迭代中,单独读取和处理一个字符。如果有两个无效字符,循环将为两者产生相同的输出。尝试使用std::getline()之类的函数将整行数据读取为std::string(不是char),而不是读取单个字符。另外,认真考虑使用getline()从cin读取所有内容(并根据需要解释字符串以获取数据) - 如果您不这样做,您会得到奇怪的(对用户而言)行为,例如丢弃输入或似乎在阅读两次。