有谁知道为什么当我在“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";
}
最佳答案
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;
}
关于c++ - Char数据类型输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59896428/