我需要限制用戶在輸入字符時輸入一個整數和字符串。我有一個整數的方法,我只需要適應它的字符。誰能幫我這個。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