繁体   English   中英

在循环中读取C中的整数后跳过scanf

[英]scanf skipped after reading in integer in C, in while loop

我有一段代码,我检查scanf的输入是否有效。 即如果scanf返回非零正数。 这是我的代码的一部分:

while(scanf(" %d",&choice)<=0){
        printf("Incorrect value entered, please re-enter\n");
    }

其中“选择”是整数。

每次运行此代码时,编译器都会在执行while循环后跳过scanf。 我得到这样的输出:


欢迎来到捕食者/猎物计算器

请输入你的名字

丹嗨丹

请选择以下选项之一:1。计算典型捕食者和猎物系统的演变2.计算特定捕食者和猎物系统的演变3.计算CUSTOM捕食者和猎物系统的演变0.退出不正确的值输入,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入-enter输入的值不正确,请重新输入输入的错误值,请重新输入

输入的值不正确,请重新输入

你能解释一下为什么会这样吗 我似乎无法在互联网上找到任何特定于整数阅读的答案。

非常感谢,

你的代码的问题是,如果用户没有输入数字,你的程序将永远循环。 这是因为scanf会反复尝试解析相同的字符串并继续失败。 你要做的就是匹配用户写的任何内容,然后再次询问一个数字:

#include<stdio.h>

int main(){
    int choice;
    while(scanf("%d",&choice) <= 0){
        scanf("%*s"); // this will parse anything the user has written
        printf("Incorrect value entered, please re-enter\n");
    }
    return 0;
}

scanf格式字符串中的*是分配抑制字符,来自scanf手册页:

'*'赋值 - 抑制字符:scanf()按转换规范的指示读取输入,但丢弃输入。 不需要相应的指针参数,并且此规范不包含在scanf()返回的成功分配计数中。

编辑首先抱怨scanf()返回成功转换的字段数。 接下来的问题是scanf会在输入中留下未转换的字符,并会尝试再次转换这些相同的字符。 在duff输入后,您可以清除输入,如下所示:

#include <stdio.h>

#define MAXCHOICE 42

int main(void)
{
    int choice, ch;
    while(scanf("%d",&choice) != 1 || choice < 1 || choice > MAXCHOICE){
        printf("Incorrect value entered, please re-enter\n");
        while((ch = getchar(stdin)) != '\n');     // clear the input
    }
    printf("Choice %d\n", choice);
    return 0;
}

计划会议:

100
Incorrect value entered, please re-enter
a
Incorrect value entered, please re-enter
5
Choice 5

可能这就是你需要的:

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int choice,repeat = 0;

    do{
        printf("Give a Number: ");
        if((scanf("%d",&choice)) != 1){
            printf("ErrorFix it!\n");
            exit(1);
        }else{
            if(choice > 0){
                printf("OK\n");
                repeat = 0;
            }else{
                printf("Incorrect value entered, please re-enter\n");
                repeat = 1;
            }
        }
    }while(repeat == 1);

    printf("Your typed %d\n",choice);
    return 0;
}

输出:

Give a Number: 0
Incorrect value entered, please re-enter

Give a Number: -5
Incorrect value entered, please re-enter

Give a Number: 10
OK
Your typed 10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM