有人知道为什么当我在“ cInputCommandPrompt”中输入多个字符时,它会循环“按”“ Y”继续,而不是像我想要的那样只显示一次。清除缓冲区吗?如果那是您所说的,但是它似乎没有用。如果有人可以帮助我,我将不胜感激。我基本上很想要它,因此当用户不输入“ Y”时它只是-从头开始循环直到输入正确的字符为止。只是不喜欢我尝试排序的多个字符输入。
void ContinueOptions()
{
bool bValid = false;
char cInputCommandPrompt = 0;
do{
std::cout << "Press ""y"" to continue: ";
std::cin >> cInputCommandPrompt;
cInputCommandPrompt = std::toupper(static_cast<unsigned char>(cInputCommandPrompt));
if (!std::cin >> cInputCommandPrompt)
{
std::cin.clear();
std::cin.ignore(100);
std::cout << "Please try again.";
}
else if (cInputCommandPrompt == 'Y')
{
bValid = true;
}
}while(bValid == false);
std::cout << "\n";
}
答案 0 :(得分:1)
if语句中存在无效条件
if (!std::cin >> cInputCommandPrompt)
应该有
if (!( std::cin >> cInputCommandPrompt ) )
至少要像下面演示程序中所示的那样重写函数。
#include <iostream>
#include <cctype>
void ContinueOptions()
{
bool bValid = false;
char cInputCommandPrompt = 0;
do{
std::cout << "Press ""y"" to continue: ";
bValid = bool( std::cin >> cInputCommandPrompt );
if ( bValid )
{
cInputCommandPrompt = std::toupper(static_cast<unsigned char>(cInputCommandPrompt));
bValid = cInputCommandPrompt == 'Y';
}
if ( not bValid )
{
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "Please try again.\n";
}
} while( not bValid );
std::cout << "\n";
}
int main(void)
{
ContinueOptions();
std::cout << "Exiting...\n";
return 0;
}