scanf check in while loop to restrict integer input

偶尔善良 提交于 2019-12-02 05:34:42

问题


I am writing a code asking the user to input 10 integers, which are then fed to him backwards. I would like to create a "scanf check" to restrict character input. The while loop works insofar that it doesn't accept char, but it skips a integer input.

int main()
{

    int i = 0, number[10] = {0};
    char buf[128] = {0};

    for (i = 0; i < 10; i++)
    {
      printf("Please input number %d : ", i+1);

         while(scanf("%d", &number[i]) != 1)
      {
         scanf("%s", &buf);
         printf("Sorry, [%s] is not a number. Please input number %d : ", &buf, i);
      }
    }

    for (i = 0; i < 10; i++)
    {
    printf("\n Number %d is %d", (10-i), number[9-i]);
    }

    return EXIT_SUCCESS;
}

回答1:


As pointed out by H2CO3, don't use scanf, an alternative is fgets and strtol:

int i, number[10] = {0};
char buf[128], *p;

for (i = 0; i < 10; i++) {
    printf("Please input number %d : ", i+1);
    while (1) {
        fgets(buf, sizeof(buf), stdin);
        if ((p = strchr(buf, '\n')) != NULL) {
            *p = '\0';
        }
        number[i] = (int)strtol(buf, &p, 10);
        if (p == buf || *p != '\0')  {
            printf("Sorry, [%s] is not a number. Please input number %d : ", buf, i + 1);
        } else {
            break;
        }  
    }
}
for (i = 0; i < 10; i++) {
    printf("\n Number %d is %d", (10-i), number[9-i]);
}
return EXIT_SUCCESS;



回答2:


The code works fine for integer also. The only mistake I found is while printing the sorry message, you are printing just i, it should be i+1.

    int i = 0, number[10] = {0};
    char buf[128] = {0};

    for (i = 0; i < 10; i++)
    {
      printf("Please input number %d : ", i+1);

         while(scanf("%d", &number[i]) != 1)
      {
         scanf("%s", &buf);
         printf("Sorry, [%s] is not a number. Please input number %d : ", &buf, i+1);
      }
    }

    for (i = 0; i < 10; i++)
    {
    printf("\n Number %d is %d", (10-i), number[9-i]);
    }


来源:https://stackoverflow.com/questions/21401136/scanf-check-in-while-loop-to-restrict-integer-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!