2012-06-18 15 views
0
#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; 
} 

내 코드는 0 값 아래 또는 위에있는 인수를 입력 할 때 작동합니다.문자열이 0 일 때 atoi를 사용합니까?

[[email protected] programming]$ ./testx 1 
Success. 
[[email protected] programming]$ ./testx -1 
Success. 
[[email protected] programming]$ ./testx 0 
Error. 

왜 작동하지 않습니까?

+2

어떻게 작동하지 않습니까? '(! 0)'이 참입니다. 유일한 문제는 "atoi returns 0"의 철자가 잘못되었다는 것입니다. –

답변

14

매우 간단합니다. atoi은 (아마도 예상대로) 0으로 변환 된 숫자를 반환합니다.

atoi을 사용할 때 변환이 실제로 성공했는지 여부를 확인하는 표준 방법이 없습니다.

당신은 당신이 더 나은 오류가 (임의의 숫자를 처리 할 때 더 나은 인터페이스 인)을 std::istringstream, std::stoi (C++ 11) 또는 strtol를 사용하여 확인과 같은 결과를 얻을 수있는 C++를 쓰기 때문에.


표준 : istringstream 예

#include <sstream> 

    ... 

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

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

표준 : 예는 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"; 

표준 : stoi (C++ 11)

#include <string> 

    ... 

int res; 

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

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

+1 'strtol'입니다. –

+0

아, 네. 좀 더 철저하게 문서를 읽었어야 지금 조금 어리 석다. 좋은 대안 솔루션에 투표하고 승인 된 답변으로 표시합니다. 감사! – Griffin

+1

C++ 11에는 예외가 발생하는'stoi'가 있습니다. – chris

3

C에서 0false 수단과 0이 아닌 값을 의미하기 때문에 true. atoi("0")은 0을 반환하므로 if 문은 else 절로 분기됩니다.

1

man-pageatoi()이 오류를 감지하지 못한다는 것을 분명히합니다. 그것은 항상 귀하의 경우 0입니다 숫자를 반환합니다.

코드가 if (!0)으로 평가되므로 오류가있는 것으로 잘못 나타냅니다.

atoi()과 함께 오류 처리를 수행 할 수있는 옵션이 없으므로 대신 strtoul()/strtol()을 사용해야합니다. (예를 들어 맨 페이지 참조).