简体   繁体   English

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

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

I have a section of code where I check the input to scanf is valid. 我有一段代码,我检查scanf的输入是否有效。 ie if scanf returns a non zero positive number. 即如果scanf返回非零正数。 This is part of my code: 这是我的代码的一部分:

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

Where “choice” is an integer. 其中“选择”是整数。

Every time I run this code, the compiler skips past the scanf after the while loops is executed. 每次运行此代码时,编译器都会在执行while循环后跳过scanf。 I get an output like this: 我得到这样的输出:


Welcome to the Predator/Prey Calculator 欢迎来到捕食者/猎物计算器

Please enter your name 请输入你的名字

Dan Hi Dan 丹嗨丹

Please choose one of the following options: 1. Calculate the evolution of a TYPICAL predator and prey system 2. Calculate the evolution of a SPECIFIC predator and prey system 3. Calculate the evolution of a CUSTOM predator and prey system 0. Quit a Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter 请选择以下选项之一:1。计算典型捕食者和猎物系统的演变2.计算特定捕食者和猎物系统的演变3.计算CUSTOM捕食者和猎物系统的演变0.退出不正确的值输入,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入输入的错误值,请重新输入-enter输入的值不正确,请重新输入输入的错误值,请重新输入

Incorrect value entered, please re-enter 输入的值不正确,请重新输入

Could you explain why this happens! 你能解释一下为什么会这样吗 I can't seem to find any answers on the internet specific to reading in integers. 我似乎无法在互联网上找到任何特定于整数阅读的答案。

Many thanks, 非常感谢,

The problem with your code is that in case the user does not input a number your program will loop forever. 你的代码的问题是,如果用户没有输入数字,你的程序将永远循环。 This is because scanf will repeatedly try to parse the same string and keep failing. 这是因为scanf会反复尝试解析相同的字符串并继续失败。 What you have to do is to match whatever the user has written and then ask again for a number: 你要做的就是匹配用户写的任何内容,然后再次询问一个数字:

#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;
}

The * in the scanf format string is the assignment suppression character, from scanf man page: scanf格式字符串中的*是分配抑制字符,来自scanf手册页:

'*' assignment-suppression character: scanf() reads input as directed by the conversion specification, but discards the input. '*'赋值 - 抑制字符:scanf()按转换规范的指示读取输入,但丢弃输入。 No corresponding pointer argument is required, and this specification is not included in the count of successful assignments returned by scanf(). 不需要相应的指针参数,并且此规范不包含在scanf()返回的成功分配计数中。

EDIT First complaint is that scanf() returns the number of fields successfully converted. 编辑首先抱怨scanf()返回成功转换的字段数。 The next problem is that scanf leaves unconverted characters in the input, and will try to convert these same characters again. 接下来的问题是scanf会在输入中留下未转换的字符,并会尝试再次转换这些相同的字符。 After a duff input, you can clear the input like this: 在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;
}

Program session: 计划会议:

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

Probably this is what you need: 可能这就是你需要的:

#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;
}

Output: 输出:

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