当字符串代表零时使用atoi?

时间:2012-06-18 12:51:46

标签: c++ g++ zero atoi

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

int main(int argc, char **argv)
{
        if(argc != 2)
                return 1;
        if(!atoi(argv[1]))
                printf("Error.");
        else printf("Success.");
        return 0;
}

当我输入的参数低于或高于零值时,我的代码才有效。

[griffin@localhost programming]$ ./testx 1
Success.
[griffin@localhost programming]$ ./testx -1
Success.
[griffin@localhost programming]$ ./testx 0
Error.

为什么不起作用?

3 个答案:

答案 0 :(得分:14)

非常简单,atoi返回转换的数字,在您的情况下正好是0(正如预期的那样)。

使用atoi时,没有标准方法可以检查转换是否成功。

由于您正在编写c ++,因此可以通过使用std::istringstreamstd::stoi(C ++ 11)或strtol(这是一个更好的界面)来获得更好的错误检查结果处理任意数字时。)


std :: istringstream示例

#include <sstream>

  ...

std::istringstream iss (argv[1]);
int res;

if (!(iss >> res))
  std::cerr << "error";

std :: strtol示例

#include <cstdlib>
#include <cstring>

  ...

char * end_ptr;

std::strtol (argv[1], &end_ptr, 10);

if ((end_ptr - argv[1]) != std::strlen (argv[1]))
  std::cerr << "error";

std :: stoi (C ++ 11)

#include <string>

  ...

int res;

try {
  res = std::stoi (argv[1]);

} catch (std::exception& e) {
  std::cerr << "error";
}

答案 1 :(得分:3)

因为C中的0表示false,任何非零值表示true。并且atoi("0")返回0,因此if语句分支到else子句。

答案 2 :(得分:1)

man-page明确指出,atoi()无法检测到错误。它始终返回一个数字,在您的情况下为0

所以你的代码评估为if (!0),这是真的,因此错误地表示错误。

没有选项可以使用atoi()进行错误处理,因此您应该使用strtoul()/strtol()。 (例如,参见联机帮助页。)