为什么 scanf 在输入无效时陷入无限循环? [英] Why does scanf get stuck in an infinite loop on invalid input?

查看:87
本文介绍了为什么 scanf 在输入无效时陷入无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在第 5 行中,我读取了一个整数,isint 如果读取的是一个整数则为 1,如果它不是整数则为 0.如果 isint 是 0,我有一个循环要求用户给出一个整数,然后我一直读到用户给出一个整数.我尝试这段代码给出一个字符而不是一个整数,但我有一个无限循环.该程序不会等待提供新的输入.我的代码有什么问题?

In line 5 I read an integer and isint is getting 1 if it reads an integer or 0 if it's not an integer. If isint is 0 I have a loop asking user to give an integer and I read until the user gives an integer. I try this code giving a character instead of an integer but I have an infinite loop. The program just doesn't wait to give a new input. What's wrong with my code?

#include <stdio.h>

int main(void) {

  int arg1;
  //int arg2;
  int attacknum = 1;
  int isint = 1;

  //printf("Insert argument attacks and press 0 when you have done this.\n");
  printf("Attack %d\n", attacknum);
  attacknum++;
  printf("Give attacking argument:");
  isint = scanf("%d", &arg1);  //line 5

  while(isint == 0){
    printf("You did not enter a number. Please enter an argument's number\n");
    isint = scanf("%d", &arg1);
    printf("is int is %d\n", isint);
  }
  return 0;
}

推荐答案

正如其他人所提到的,如果 scanf 无法解析输入,它会使其未扫描.

As others have mentioned, if scanf can't parse the input, it leaves it unscanned.

通常 scanf 是交互式输入的糟糕选择,因为这种行为,并且因为它与用户体验的一次一行的界面不匹配.

Generally scanf is a poor choice for interactive input because of this kind of behavior, and because it doesn't match the line-at-a-time interface experienced by the user.

最好使用 fgets 将一行读入缓冲区.然后使用 sscanf 解析该行.如果您不喜欢输入,请将整行扔掉并阅读另一行.

You are better off reading one line into a buffer using fgets. Then parse that line using sscanf. If you don't like the input, throw the whole line away and read another one.

像这样:

#include <stdio.h>

int main(void)
{
  char line[256];

  int arg1;
  int isint;

  while (1) {
    printf("Give attacking argument:");
    fgets(line, sizeof line, stdin);
    isint = sscanf(line, "%d",&arg1);
    if (isint) break;

    printf("You did not enter a number.Please enter an argument's number\n");
  }

  printf("Thanks for entering %d\n", arg1);

  return 0;
}

(对于生产代码,您需要处理长行,检查返回代码,还检查数字后面的尾随垃圾等)

(For production code you'll want to handle long lines, check return codes, also check for trailing garbage after the number, etc.)

实际上,如果您只想读取整数,则更好的方法是不要使用 scanf,而是使用 strtol.这为您提供了一个指向数字后面字符的方便指针,您可以检查它是空格还是空.

Actually, an even better approach would be to not use scanf if you just want to read an integer, and instead use strtol. That gives you a handy pointer to the character just after the number, and you can check that it's whitespace or nul.

这篇关于为什么 scanf 在输入无效时陷入无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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