简体   繁体   English

清除 C 中不正确的 scanf 输入

[英]Clearing incorrect scanf inputs in C

I have scoured the internet and my textbooks and lectures for a way to fix this issue and nothing appears to be working.我已经在互联网和我的教科书和讲座上搜索了解决此问题的方法,但似乎没有任何效果。

I am using scanf to get an integer input, and need to validate the correct input.我正在使用 scanf 来获取整数输入,并且需要验证正确的输入。

However, when I put say, two characters or two numbers with a space inbetween into the scanf, it runs through twice instead of once as scanf hangs on to the unused data.但是,当我将两个字符或两个中间有空格的数字放入 scanf 时,它会运行两次而不是一次,因为 scanf 会挂在未使用的数据上。

I cannot for the life of me find out how to either clear the scanf data, or to get it to read all of the input together as one incorrect input.我一生都无法找出如何清除 scanf 数据,或让它将所有输入一起读取为一个不正确的输入。 I know how to clear the \\n, just not the trailing characters that get left in the input.我知道如何清除 \\n,而不是在输入中留下的尾随字符。

int scan;
bool validInput = false;
int validScan;
int count = 0;
do 
{
    puts("Enter pin : ");
    validScan = scanf("%d", &scan);
    ((getchar()) != '\n');

    if(validScan !=1)
    {
        count++;
        puts("Incorrect pin entered.");
    }
    else if(scan != PIN)
    {
        count++;
        puts("Incorrect pin entered.");
    }
    else
    {
        validInput = true;
        count = 3;
    }
} while (count < 3);
return validInput;

However, when I put say, two characters or two numbers with a space inbetween into the scanf, it runs through twice instead of once as scanf hangs on to the unused data.但是,当我将两个字符或两个中间有空格的数字放入 scanf 时,它会运行两次而不是一次,因为 scanf 会挂在未使用的数据上。

You need to decouple the interpretation of the user input from reading the user input.您需要将用户输入的解释与读取用户输入分离。

So instead of using scanf that does both at the same time:因此,不要使用同时执行这两项操作的scanf

int num1, num2;
bool success = (scanf("%d %d", &num1, &num2) == 2);

Use fgets to read it and sscanf to interpret it:使用fgets读取它并使用sscanf来解释它:

char buf[1024];
bool success = false;
if(fgets(buf, 1024, stdin) != NULL)
    success = (sscanf(buf, "%d %d", &num1, &num2) == 2);

See also scanf vs fgets .另请参阅scanf 与 fgets

you could use fflush(stdin);你可以使用fflush(stdin); before a scanf to clean the input.在 scanf 之前清理输入。

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

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