我需要限制用户在输入字符时输入一个整数和字符串。我有一个整数的方法,我只需要适应它的字符。谁能帮我这个。Validator for one char for user input
char getChar()
{
char myChar;
std::cout << "Enter a single char: ";
while (!(std::cin >> myChar))
{
// reset the status of the stream
std::cin.clear();
// ignore remaining characters in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ^^^ This line needs to be changed.
std::cout <<
"Enter an *CHAR*: ";
}
std::cout << "You entered: " << myChar << std::endl;
return myChar;
}
char getChar()
{
char myChar;
std::cout << "Enter an Char: ";
while (!(cin >> myChar))
{
// reset the status of the stream
cin.clear();
// ignore remaining characters in the stream
cin.ignore(std::numeric_limits<char>::max() << '\n');
cout << "Enter an *CHAR*: ";
}
std::cout << "You entered: " << myChar << std::endl;
return myChar;
}
我试过这个,没有错误。但它并没有发生。
我想不出一种'cin >> myChar'可能因非法转换而失败的方式(例如''0'是一个合法的'char')。读取后您需要检查'myChar'的值。 – hmjd