微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当输入的是字符或单词时,不显示“无效输入”

如何解决当输入的是字符或单词时,不显示“无效输入”

当输入为 >2<0 时,显示“无效输入。”。但是当输入的是字母或单词时,它不会显示“无效输入”。

int main()
{
    int userInput,gesture;

    cout << "Rock(0),Paper(1),Scissor(2): ";
    cin >> userInput;

    srand(time(0));
    gesture = rand() % 3;

    if (isdigit(userInput) && userInput >= 0 || userInput <= 2)        //I think it's a logic error,but idk how to fix it.
    {
        switch (gesture)
        {
        case (0):
            if (userInput == gesture)
                cout << "The computer is rock. You are rock too. It is a draw." << endl;
            else if (userInput == 1 && gesture == 0)
                cout << "The computer is rock. You are paper. You win." << endl;
            else if (userInput == 2 && gesture == 0)
                cout << "The computer is rock. You are scissor. You lose." << endl;
            break;
       
        }
    }

    else  
        cout<<"Invalid input.";

    return 0;
}

解决方法

让我们看看这个:

if (isdigit(userInput) && userInput >= 0 || userInput <= 2)  

isdigit 的签名是这样的:

int isdigit( int ch );

所以人们可能会误以为它期望一个 int,例如 1 或 34。实际上,它期望一个 unsigned char 类型的参数转换为一个 int。为什么,你会问?因为它是通过 C 语言的标准库包含在 C++ 中的,而且在 C 中有一个特殊的标记 EOF,它标记字符流中的“文件结尾”(就像 \0 标记字符串的结尾)。问题是 EOF 不能表示为 char,因此许多旨在处理字符串的 C 函数接受 int。我们对 EOF 的唯一了解是它是否定的。

所以,isdigit 的通常用法是这样的:

unsigned char c = '0';
// ...
if (isdigit(c)) { /* ... */ } 

那你该怎么办? 嗯,越简单越好

  if (userInput >= 0 && userInput <= 2)  

如果要检查完全无效的用户输入,请检查 cin

的状态
  if (std::cin && userInput >= 0 && userInput <= 2)  

另一种方法是用一个明显错误的值初始化 userInput,例如与-1。如果 cin 失败,您无论如何都会知道发生了错误,因为 userInput 会有一个无效值 -1

使用 std::cin.clear() 清除 std::cin 中的“失败状态”标志并取消阻止。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。