检查输入可能的Int溢出

问题描述 投票:3回答:2

我已经阅读了一段时间的源代码,但他们总是在讨论操作时的溢出但是如何在用户输入可能被分配给int标识符之前检查潜在的int溢出?

我想在输入的那一刻检查输入,所以当发现这样的值已经超出了int类型数据的值范围时,我可以在它进入代码的下一部分之前停止它。

c
2个回答
7
投票

你可以读取一个字符串然后使用strtol然后检查endptr和errno,当一切正常时你可以分配你的int var

详细使用strtol

#include <stdlib.h>
#include <ctype.h>
#include <errno.h>

int main()
{
  char s[32]; /* 31 characters is surely large enough for an int */

  if (scanf("%31s", s) != 1)
    puts("nok");
  else {
    errno = 0;

    char * endptr;
    long int l = strtol(s, &endptr, 10);

    if (endptr == s)
      puts("no digit");
    else if ((*endptr != 0) && !isspace(*endptr))
      puts("invalid number");
    else if (errno != 0)
      puts("overflow on long");
    else if (((int) l) != l) /* in case long and int do not have the same size */
      puts("overflow on int");
    else
      puts("you enter a valid int");
  }

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra s.c
pi@raspberrypi:/tmp $ ./a.out
a 
no digit
pi@raspberrypi:/tmp $ ./a.out
12z
invalid number
pi@raspberrypi:/tmp $ ./a.out
123
you enter a valid int
pi@raspberrypi:/tmp $ ./a.out
12345678901
overflow on long

所以要正确回答这个问题:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>

int readInt(int * v)
{
  char s[32]; /* 31 characters is surely large enough for an int */

  if (scanf("%31s", s) != 1)
    return 0;
  else {
    errno = 0;

    char * endptr;
    long int l = strtol(s, &endptr, 10);

    if ((endptr == s) ||       /* no digit */
        ((*endptr != 0) && !isspace(*endptr)) || /* e.g. 12a */
        (errno != 0) ||        /* overflow on long */
        (((int) l) != l))      /* overflow on int */
      return 0;

    *v = (int) l;
    return 1;
  }
}


int main()
{
  int v = 123;

  if (readInt(&v))
    printf("new valid in value : %d\n", v);
  else
    printf("unvalid input, still %d\n", v);

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra s.c
pi@raspberrypi:/tmp $ ./a.out
12
new valid in value : 12
pi@raspberrypi:/tmp $ ./a.out
9878787878787878
unvalid input, still 123
pi@raspberrypi:/tmp $ 

1
投票

如果必须直接读入int,则在分配之前无法真正检查溢出。

如果不直接读入int是有必要的话。例如,您可以读入字符缓冲区/字符串,然后检查输入是否为数字以及是否适合int。如果是这样,则使用标准库函数将字符缓冲区转换为整数并分配给int。

© www.soinside.com 2019 - 2024. All rights reserved.