防止读取和返回字符串值

时间:2014-11-08 11:31:43

标签: c

int getIndex(){
    int index = 0;
    do{
        printf("Enter your Index(0..80),-1 to STOP,-2 to RESTART,-3 to START NEW BOARD: ");
        scanf("%d", &index);
    } while (!(index >= -3 && index <=80));

    return index;

}

您好,因为我已经在C中为数独游戏棋盘编写了上述方法。我该怎么做才能阻止用户输入字母?并继续提示,直到获得有效输入。我刚开始使用C。什么是限制我是scanf标志说明符,我指定了一个int标志,这意味着如果用户输入一个字符串,我搞砸了。

1 个答案:

答案 0 :(得分:2)

如果输入了任何无效输入,您只需检查scanf的返回值,然后从输入缓冲区(stdin)中清除该字符。因此,请将代码更改为以下内容:

int getIndex()
{
    int index = 0;

    while(1) //infinite loop
    {    printf("Enter your Index(0..80),-1 to STOP,-2 to RESTART,-3 to START NEW BOARD: ");
        if(scanf("%d", &index)==1) //scanf is successful scanning a number(input is a number)
        {
          if(index >= -3 && index <= 80) // if input is in range
          break; //break out of while loop
          printf("Number must be in range of -3 to 80\n"); //input is a number,but not in range
        }
        else  //input is not a number
        {
        scanf("%*s"); //Clear invalid input
        //printf("Invalid input\n");
        fprintf(stderr, "Invalid input\n"); //printf also works but errors are meant to be in the stderr
        }

    }

    return index;
}