Char 数据类型的输入问题
Problems with Inputs to Char Datatype
有谁知道为什么当我在 "cInputCommandPrompt" 中输入多个字符时,它会循环 "Press "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;
}
有谁知道为什么当我在 "cInputCommandPrompt" 中输入多个字符时,它会循环 "Press "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;
}