C语言 在调用 atoi() 之前如何检查以确保您有一个整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3850558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:35:57  来源:igfitidea点击:

How to check to ensure you have an integer before calling atoi()?

ccastingatoi

提问by cilk

I wish to take an integer as a command line argument, but if the user passes a non-integer string, this will cause a stack overflow. What is the standard way to ensure atoi() will be successful?

我希望将一个整数作为命令行参数,但是如果用户传递一个非整数字符串,这将导致堆栈溢出。确保 atoi() 成功的标准方法是什么?

回答by zserge

You can use:

您可以使用:

long int strtol(const char *nptr, char **endptr, int base);

long int strtol(const char *nptr, char **endptr, int base);

Then check if *endptr != nptr. This means that the string at least begins with the integer. You can also check that *endptr points to terminating zero, which means that the whole string was successfully parsed.

然后检查是否*endptr != nptr。这意味着字符串至少以整数开头。您还可以检查 *endptr 是否指向终止零,这意味着整个字符串已成功解析。

回答by e2-e4

atoi()will (should) not cause a stack overflow if the string contains characters other than digits. It will simply convert to an intany digit it finds from the beginning of the string until there is no more.

atoi()如果字符串包含数字以外的字符,将(应该)不会导致堆栈溢出。它将简单地转换为int它从字符串开头找到的任何数字,直到没有更多数字。

  int x = atoi("12monkeys"); // x is 12
  int y = atoi("monkeys12"); // y is 0

You may check that there is no integer overflow(number outside the range of [-2^31, 2^31-1] on a modern (current) PC architecture).

您可以检查是否没有整数溢出(现代(当前)PC 架构上的 [-2^31, 2^31-1] 范围之外的数字)。

edit(comments)

编辑(评论)

While the C standards warns about an undefined behaviorif the value cannot be represented, the most common C recent compilers (gcc, MS...) do not crashif the value is not acceptable (unless the char *pointer is null or wrong of course).

虽然 C 标准会在值无法表示时警告未定义的行为,但如果值不可接受,最常见的 C 最近编译器(gcc、MS...)不会崩溃(当然,除非char *指针为空或错误) .

Anyway, you can implement your own atoi()easily (with the same limitations as in my answer)

无论如何,您可以atoi()轻松实现自己的(具有与我的答案相同的限制)

    #include <ctype.h>

    int myatoi(char *s) {
       int res = 0, minus = *s == '-';
       if (minus) s++;

       while (isdigit(*s)) {
          res = res*10 + (*s++ - '0');
       }

       return minus ? -res : res;
    }

回答by Amadan

This does not cause stack overflow. atoireturns 0if it can't find a number at the start of the string. Your (non-)handling of the 0is what causes the stack overflow.

这不会导致堆栈溢出。如果在字符串的开头找不到数字,则atoi返回0。您对 的(非)处理0是导致堆栈溢出的原因。

回答by Cornul11

atoi()is converting the string to an integer if it contains only digit chars, otherwise it will return 0.

atoi()如果字符串仅包含数字字符,则将字符串转换为整数,否则将返回 0。

回答by R.. GitHub STOP HELPING ICE

Cause a stack overflow? Well I suppose that's one possible result of the undefined behaviorif the value in the string overflows the range of int. In practice though it usually just wraps or returns a bogus result.

导致堆栈溢出?好吧,我想这是未定义行为的一种可能结果,如果字符串中的值超出int. 在实践中,虽然它通常只是包装或返回一个虚假的结果。

If you want better error checking, use strtolinstead of atoi. It has well-defined behavior on overflow (it sets errno, which you need to clear to 0 before calling strtolso you can distinguish between error returns and legitimate values being returned) and you can examine the point in the string at which it stopped conversion to see if the full string was an integer or whether there's additional content past the end.

如果您想要更好的错误检查,请使用strtol代替atoi。它在溢出时具有明确定义的行为(它设置errno,您需要在调用之前将其清除为 0,strtol以便您可以区分错误返回和返回的合法值)并且您可以检查字符串中停止转换的点以查看如果完整字符串是一个整数,或者末尾是否还有其他内容。

回答by Sachin Shanbhag

This might help you. Check strtolavailable in stdlib.h

这可能对你有帮助。检查stdlib.h 中可用的strtol

回答by Michiel Boekhoff

Either you can do this and enter Undefined Behavior land, you could write a simple validation function like so:

您可以这样做并进入未定义行为领域,您可以编写一个简单的验证函数,如下所示:

/* returns 0 on success, 1 on failure. */

int verify(char * string)
{
    int x = 0;
    int len = strlen(string);

    while(x < len) {
           if(!isdigit(*(string+x)))
           return 1;

           ++x;
    }

    return 0;
}

Please note you do have to call this function beforeyou call atoi(), and you need string.h and stdio.h.

请注意,您必须调用 atoi()之前调用此函数,并且需要 string.h 和 stdio.h。

回答by Lou Franco

I don't think a standard atoi will stackoverflow, but there's no way to tell if you don't have an integer with it. Use strtolinstead -- it's possible to deal with non-integers.

我认为标准的 atoi 不会stackoverflow,但是没有办法判断你是否没有整数。使用strtol代替-这是可以处理非整数。

http://en.wikipedia.org/wiki/Strtol

http://en.wikipedia.org/wiki/Strtol