【问题标题】:Checking if user inputted right character检查用户是否输入了正确的字符
【发布时间】:2019-03-09 07:30:47
【问题描述】:

我试图弄清楚如何确保用户输入正确的字符。基本上,我希望用户输入 c 或 u。到目前为止,它一直有效,直到用户输入以 u 或 c 开头的短语,它仍然可以通过。我希望他们只按 c 或 u 而不在字母上附加任何其他字符。我认为这与数组有关,但我对数组的了解并不多。这里:

#include <stdio.h>

int main()
{
    char turn;

    printf("Welcome to the game of Sticks. The objective is to pick up the last stick\n\n");
    printf("Please choose who goes first. (u for user and c for computer): ");
    scanf(" %c", &turn);

    while (turn != 'c' && turn != 'u')          //Checking if user inputted c or u
    {
        printf("\nPlease enter u to go first or c for computer to go first!\n");
        scanf(" %c", &turn);
    }

    return 0;
}

【问题讨论】:

    标签: arrays input char


    【解决方案1】:

    你不应该使用==比较运算符来比较字符串...

    改为使用strncmp 函数,在"string.h" 中定义

    例如,

    #include <stdio.h>
    #include <string.h>
    
    int main(void){
    
      char turn[] = "";
    
      scanf("%c",&turn);      
    
      while(strncmp(turn,'c',sizeof('c')) != 0) && (strncmp(turn,'u',sizeof('u')) != 0){
        //If User didn't enter c or u
        scanf("%c",&turn);
    
      }
    
     return 0;
    
    }
    

    哦,另外,请始终确保初始化您在函数中定义的变量,例如,通过执行以下操作初始化 turn 变量:char turn = "";

    这是为了防止turn变量在内存地址中被分配一个随机值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多