当您将 12ab 之类的内容输入到 scanf("%d",&argu) 时会发生什么? [英] what happens when you input things like 12ab to scanf("%d",&argu)?

查看:33
本文介绍了当您将 12ab 之类的内容输入到 scanf("%d",&argu) 时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想检查我输入的是数字时遇到了这个问题.如果我成功输入一个数字,scanf 函数将返回 1.所以这是我写的:

I came across this problem when I want to check what I input is number. The scanf function will return 1 if I successfully input a number. So here is what I wrote:

int argu;
while(scanf("%d",&argu)!=1){
    printf("Please input a number!\n");
}

但是当我向它输入诸如 abcd 之类的东西时,循环将永远运行并且不会因提示而停止.

But when I input things like abcd to it, the loop would go forever and not stop for prompt.

我在网上查了一下,发现它与缓存有关,我需要清理它以便 scanf 可以获取新数据.所以我尝试了 fflush 但它没有用.

I looked it up online and found that it had something to do with the cache and I need to clean it up so scanf can get new data. So I tried fflush but it didn't work.

然后我看到了这个:

int argu,j;
while(scanf("%d",&argu)!=1){
    printf("Please input a number!\n");
    while((j=getchar())!='\n' && j != '\n');
}

然后,当我输入诸如abcd"之类的内容时,它运行良好并提示我输入.但是当我输入诸如12ab"之类的东西时,它就无法再工作了.

Then when I input things like 'abcd' it worked well and it prompted for my input. But when I input things like '12ab', it wouldn't work again.

那么有什么方法可以检查 scanf("%d", &argu) 的输入实际上是一个数字,如果不是,则提示输入另一个输入?

So is there a way I can check the input for scanf("%d", &argu) is actually a number and prompt for another input if it isn't?

编辑:

我看到答案并使用 while(*eptr != '\n') 解决了我的问题.

I saw the answers and solved my problem by using while(*eptr != '\n').

请注意,fgets 函数实际上将 '\n' 读入数组,而 gets 不会.所以要小心.

Notice that the fgets function actually reads '\n' into the array and gets doesn't. So be careful.

推荐答案

最好读一整行,使用 fgets(),然后检查它,而不是试图解析在飞行"从输入流.

It's better to read a full line, using fgets(), and then inspecting it, rather than trying to parse "on the fly" from the input stream.

这样更容易忽略无效输入.

It's easier to ignore non-valid input, that way.

先用fgets()再用strtol()转成数字,这样可以很容易看出数字后面是否有尾随数据.

Use fgets() and then just strtol() to convert to a number, it will make it easy to see if there is trailing data after the number.

例如:

char line[128];

while(fgets(line, sizeof line, stdin) != NULL)
{
   char *eptr = NULL;
   long v = strtol(line, &eptr, 10);
   if(eptr == NULL || !isspace(*eptr))
   {
     printf("Invalid input: %s", line);
     continue;
   }
   /* Put desired processing code here. */
}

这篇关于当您将 12ab 之类的内容输入到 scanf("%d",&argu) 时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆