C:如何用scanf函数溢出至prevent输入? [英] C: How to prevent input using scanf from overflowing?

查看:210
本文介绍了C:如何用scanf函数溢出至prevent输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的C和想知道如何prevent从输入溢出...

I'm relatively new to C and would like to know how to prevent an overflow from input...

因此​​,例如,我有:

So for example, I have:

scanf("%d", &a);

其中a是整数

所以我我可以做些什么来进入一个数字,比最大的整数更大prevent人吗?由于问题的约束我的工作,你必须使用 scanf函数。我该如何去限制输入?

So what I could I do to prevent someone from entering a number that's larger than max integer? Due to the constraints of the problem I'm working on, you HAVE to use scanf. How do I go about restricting the input?

先谢谢了。

推荐答案

提斯非常具有挑战性的 prevent 的用户输入。结果
有没有神奇的手,伸手从在键盘上跳动走停止用户。

'Tis very challenging to prevent user input.
There is no magic hand to reach out and stop the user from beating away at the keyboard.

不过,code可以限制它的读取。

But code can limit what it reads.

1) scanf()的是很难限制。它可能没有设置错误号上溢出。 code可以限制字符数说9.这是第一步,但类似10亿或00000000000000001一个人不能输入值。

1) scanf() is tough to limit. It may not set errno on overflow. Code can limit the number of char to say 9. That's a first step but one can not enter values like "1000000000" or "00000000000000001".

// Assume INT_MAX = 2,147,483,647.
scanf("%9d", &a);

2)迂腐方法将使用龟etc()。一个无符号方法如下。 INT 需要多一点。

2) A pedantic method would use fgetc(). An unsigned method follows. int takes a bit more.

unsigned a = 0;
int ch = fgetc(stdin);
while (isspace(ch)) {
  ch = fgetc(stdin);
}
while (isdigit(ch)) {
  unsigned newa = a*10 + ch - '0';
  if (newa < a) {
    break;  // overflow detected.
  }
  a = newa;
  ch = fgetc(stdin);
}
ungetc(ch, stdin);  // Put back `ch` as it was not used.       

3)但是我preFER改变的目标,只是再次告诉用户,即使这意味着读多个字符。

3) But I prefer to change the goal and simply tell the user again, even if it mean reading in more characters.

// 0:success or EOF
int Read_int(const char *prompt, int *dest, int min, int max) {
  for (;;) {
    char buf[sizeof(int)*3 + 3];
    fputs(prompt, stdout);
    if (fgets(buf, sizeof buf, stdin) == NULL) {
      return EOF;
    }
    char *endptr;
    errno = 0;
    long l = strtol(buf, &endptr, 10);
    if (buf == endptr || *endptr != '\n') {
      continue; // only \n entered or invalid `chars` entered
    }
    if (!errno && l >= min && l <= max) {
     *dest = (int) l;
     return 0; // success
    }
  }
}  

int a;
Read_int("Enter an `int`\n", &a, INT_MIN, INT_MAX);

这篇关于C:如何用scanf函数溢出至prevent输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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