首页 > 解决方案 > 为什么这段代码没有正确重新提示?

问题描述

我对 C 完全陌生。当输入值不是数字时,我想重新提示,当它是数字时,它应该小于 1。当我给出任何类型的字符串时,它都能正常工作。但是当我给出任何数字时,它会转到下一行而不打印“Number:”。然后在下一行,如果输入值小于 1,它会再次打印“Number:”。

int x;
printf("Number: ");
while (scanf("%d", &x) != 1 || x < 1 )
{

    printf("Number: ");

    scanf("%*s");
}

它给我的结果是这样的

结果

标签: cwhile-loop

解决方案


fgets使用读取行,然后使用sscanf解析输入是明智的。这样就可以拿到线,然后检查是否sscanf成功!简单的例子:

int target_number; // The number you will have at the end of this.
while (1) { // Loop for rechecking number
    char line[16]; // See notes on how to read the whole line.
    fgets(line, sizeof(line), stdin);

    // We use 1 here because sscanf returns the number of format specifiers that are matched. Since you only need one number, we use 1.
    if (sscanf(line, "%d", &target_number) != 1) {
        fprintf(stderr, "Invalid Input! Please enter in a valid number.");
        continue;
    }
}

// Do whatever you will with target_number

笔记

您可以在此处查看如何阅读整行。

这段代码不安全!

它不能防止缓冲区溢出攻击等。请以正确的方式查看此内容如果这只是为了学习,你不必担心。


推荐阅读