输入字符时,我需要限制用户输入整数和字符串。我有一个整数的方法,我只需要将它改成char。谁能帮我这个。

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;
}

我已经尝试过了,没有错误。但这并没有发生。

最佳答案

我猜测“无效”是指即使您输入了更长的字符串或数字,它仍然可以接受。这是因为通过<<运算符输入的所有字母和数字仍然是单个字符。

如果您不想使用非字母字符,则必须添加另一个检查:

while (!(std::cin >> myChar) || !std::isalpha(mychar))

有关std::isalpha的说明,请参见this reference

关于c++ - 用于用户输入的单个字符的验证器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12840301/

10-16 11:03
查看更多