提示用户询问输入,直到满足条件?

时间:2018-09-26 09:51:11

标签: c loops do-while counting

int32_t number;
uint32_t x = 1;

puts("What number do you want to count: ?");
{
    scanf("%i", &number);
    printf("You typed%i.\n", number);
    while(x < number) {
        printf("%i and then \n", x);
        x++;
    }
    if (x > 100 || x < 1)
        printf("error");
}

我要打印所有数字,直到用户输入数字为止。但是,如果输入的数字小于1或大于100,则它应该说错误并要求用户再次输入数字,但不会这样做。例如,如果数字是455,它应该说出错误并提示用户再次输入数字。上面的程序仅在打印所有偶数格或小于100或小于1的数字后才打印错误。

1 个答案:

答案 0 :(得分:1)

#include <stdint.h>
#include <stdio.h>

int main(void)
{
    int32_t number;

    while (puts("What number do you want to count? "),  // prompt the user
           scanf("%i", &number) != 1                    // reading an int failed
           || number < 1 || 100 < number)               // number not in range
    {
        fputs("Error!\n\n", stderr);       // print an error message
        int ch;
        while ((ch = getchar()) != EOF && ch != '\n');  // remove garbage left in stdin
    }

    printf("You typed %d.\n", number);

    for(int32_t i = 0; i < number; ++i)
        printf("%i and then\n", i);
}