为什么非整数输入会导致无限循环?

时间:2019-12-03 00:14:27

标签: c

当我输入非整数值时,会导致无限循环。我需要更换scanf吗?如果是这样,我该怎么做。

int num=1;
if(num==1){
  int slct;
  printf("\n\tWelcome");
  printf("\n1. Login\n2. Register\n3. Account\n4. Exit\n");
  SELECTION: ;
  printf("\n\tEnter a number:");
  scanf("%d",&slct);
  if (slct == 1){}
  else if (slct == 2){}
  else if (slct == 3){}
  else if (slct == 4){
    return 0;
  } else {
    goto SELECTION;
  }
}

1 个答案:

答案 0 :(得分:2)

您需要检查scanf的返回值并刷新输入:

#include <stdbool.h>
#include <stdio.h>

int main()
{
    bool done = false;
    while (!done) {
        printf("\n\tWelcome\n");
        printf("1. Login\n");
        printf("2. Register\n");
        printf("3. Account\n");
        printf("4. Exit\n\n");
        printf("Enter a number:");
        int selection;
        int result = scanf("%d", &selection);
        if (EOF == result) {
            done = true;
        }
        else if (1 != result) {
            printf("You did not enter a valid number\n");
            int c;
            while ((c = getchar()) != '\n' && c != EOF) {}
            done = (c == EOF);
        }
        else if (1 == selection) {
            printf("You chose login\n");
        }
        else if (2 == selection) {
            printf("You chose register\n");
        }
        else if (3 == selection) {
            printf("You chose account\n");
        }
        else if (4 == selection) {
            done = true;
        }
        else {
            printf("Please pick a number between 1 and 4\n");
        }
    }
}

scanf("%d",&slct);中的格式字符串为%d,表示您要读取数字。

输入数字以外的其他内容时,scanf返回0表示已读取零个数字。

如果scanf在尝试读取输入时遇到文件结尾(输入control-D),则它将返回特殊值EOF。

此外,scanf不会消耗不正确的输入,因此您需要显式刷新它。