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

Gri*_*fin 0 c++ g++ atoi zero

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

[griffin@localhost programming]$ ./testx 1
Success.
[griffin@localhost programming]$ ./testx -1
Success.
[griffin@localhost programming]$ ./testx 0
Error.
Run Code Online (Sandbox Code Playgroud)

为什么不起作用?

Fil*_*efp 14

它非常简单,atoi返回转换的数字,在您的情况下完全0(如预期的那样).

使用时,没有标准方法检查转换是否实际成功atoi.

既然你正在编写C++,你可以得到相同的结果具有较好的错误使用检查std::istringstream,std::stoi(C++ 11)或strtol(这是任意数字打交道时更好的接口).


std :: istringstream示例

#include <sstream>

  ...

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

if (!(iss >> res))
  std::cerr << "error";
Run Code Online (Sandbox Code Playgroud)

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";
Run Code Online (Sandbox Code Playgroud)

std :: stoi(C++ 11)

#include <string>

  ...

int res;

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

} catch (std::exception& e) {
  std::cerr << "error";
}
Run Code Online (Sandbox Code Playgroud)