C程序无限循环scanf函数获取意外的数据后, [英] C program loops infinitely after scanf gets unexpected data

查看:198
本文介绍了C程序无限循环scanf函数获取意外的数据后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,我想输入整型为2和64(含)之间,所以我把 scanf函数做{.. },而循环。这里的code我最初测试:

I have a program where I want the input integer to be between 2 and 64 inclusive, so I put scanf inside a do { ... } while loop. Here's the code I initially tested:

int initialBase;

do {
  printf("Initial base: ");
  scanf("%i", &initialBase);
} while (initialBase < 2 || initialBase > 64);

问题是每当输入不是一个有效的整数,它只是无限期输出的printf 语句,不再提示用户输入,瞬间充斥控制台。这是为什么发生的,什么是阅读输入满足我想要的条件,更好的办法?

The problem is whenever the input is not a valid integer, it just outputs the printf statement indefinitely and no longer prompts for user input, instantly flooding the console. Why is that happening and what's a better way of reading input that satisfies the conditions I want?

推荐答案

scanf()的失败,参数不自动初始化,初始化值可以是任何值,所以它可能会比 64 小于 2 或更大,没有人知道。

When scanf() fails, the argument is not automatically initialized, and uninitialized values could be any value, so it might be less than 2 or greater than 64 no one knows.

试试这个

int initialBase;

/* some default value would be good. */
initialBase = 2;
do {
  printf("Initial base: ");
  if (scanf("%i", &initialBase) != 1)
      break;
} while ((initialBase < 2) || (initialBase > 64));

该检查将退出循环,如果你输入的东西是不是一个数字,的initialiazation initialBase 只是它在你的情况可能有$个好习惯p $ pvented您所描述的行为,但在这种情况下,它的存在为prevent访问,而循环后未初始化值。

the check will break out of the loop if you input something that is not a number, the initialiazation of initialBase is just a good habit which in your case could have prevented the behavior you describe, but in this case it's there to prevent accessing an uninitialized value after the while loop.

究其原因,循环并没有停止,是因为 scanf()的留下了一些字符的输入流中时,他们不匹配,并调用 scanf()的再而这些字符仍然存在将使 scanf()的继续等待有效的输入,但是与当前无效输入立刻返回这是在流,如果你想继续阅读,尝试从流中读取字符,直到一个的'\\ n'被发现,这样

The reason the loop didn't stop, was because scanf() leaves some characters in the input stream when they are not matched, and calling scanf() again while those characters are still there will make scanf() keep waiting for valid input, but returning immediatly with the currently invalid input that is in the stream, if you want to keep reading, try reading characters from the stream until a '\n' is found, this way

int initialBase;

initialBase = 0;
do {
    printf("Initial base: ");
    if (scanf("%i", &initialBase) != 1)
    {
        while (fgetc(stdin) != '\n');
        continue;
    }
} while ((initialBase < 2) || (initialBase > 64));

这篇关于C程序无限循环scanf函数获取意外的数据后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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