Namespaces
Variants

std:: atoi, std:: atol, std:: atoll

From cppreference.net
헤더 파일에 정의됨 <cstdlib>
int atoi ( const char * str ) ;
(1)
long atol ( const char * str ) ;
(2)
long long atoll ( const char * str ) ;
(3) (C++11 이후)

str 이 가리키는 바이트 문자열에서 정수 값을 해석합니다. 암시된 기수는 항상 10입니다.

첫 번째 공백 문자가 아닌 문자를 찾을 때까지 모든 공백 문자를 버린 다음, 유효한 정수 숫자 표현을 형성하기 위해 가능한 많은 문자를 가져와 정수 값으로 변환합니다. 유효한 정수 값은 다음 부분으로 구성됩니다:

  • (선택적) 양수 또는 음수 부호
  • 숫자

결과 값을 나타낼 수 없는 경우, 즉 변환된 값이 해당 반환 타입의 범위를 벗어나면 동작은 정의되지 않습니다.

목차

매개변수

str - 해석할 null로 종료되는 바이트 문자열을 가리키는 포인터

반환값

성공 시 str 내용에 해당하는 정수 값.

변환을 수행할 수 없는 경우, 0 이 반환됩니다.

가능한 구현

template<typename T>
T atoi_impl(const char* str)
{
    while (std::isspace(static_cast<unsigned char>(*str)))
        ++str;
    bool negative = false;
    if (*str == '+')
        ++str;
    else if (*str == '-')
    {
        ++str;
        negative = true;
    }
    T result = 0;
    for (; std::isdigit(static_cast<unsigned char>(*str)); ++str)
    {
        int digit = *str - '0';
        result *= 10;
        result -= digit; // INT_MIN, LONG_MIN 등을 지원하기 위해 음수로 계산
    }
    return negative ? result : -result;
}
int atoi(const char* str)
{
    return atoi_impl<int>(str);
}
long atol(const char* str)
{
    return atoi_impl<long>(str);
}
long long atoll(const char* str)
{
    return atoi_impl<long long>(str);
}

실제 C++ 라이브러리 구현들은 C 라이브러리 구현으로 되돌아가서 atoi , atoil , 그리고 atoll 을 구현하는데, 이는 직접 구현하거나 (예: MUSL libc ) strtol / strtoll 에 위임합니다 (예: GNU libc ).

예제

#include <cstdlib>
#include <iostream>
int main()
{
    const auto data =
    {
        "42",
        "0x2A", // "0"과 쓰레기 값 "x2A"로 처리됨, 16진수로 처리되지 않음
        "3.14159",
        "31337 with words",
        "words and 2",
        "-012345",
        "10000000000" // 참고: int32_t 범위를 벗어남
    };
    for (const char* s : data)
    {
        const int i{std::atoi(s)};
        std::cout << "std::atoi('" << s << "') is " << i << '\n';
        if (const long long ll{std::atoll(s)}; i != ll)
            std::cout << "std::atoll('" << s << "') is " << ll << '\n';
    }
}

가능한 출력:

std::atoi('42') is 42
std::atoi('0x2A') is 0
std::atoi('3.14159') is 3
std::atoi('31337 with words') is 31337
std::atoi('words and 2') is 0
std::atoi('-012345') is -12345
std::atoi('10000000000') is 1410065408
std::atoll('10000000000') is 10000000000

참고 항목

(C++11) (C++11) (C++11)
문자열을 부호 있는 정수로 변환
(함수)
(C++11) (C++11)
문자열을 부호 없는 정수로 변환
(함수)
바이트 문자열을 정수 값으로 변환
(함수)
바이트 문자열을 부호 없는 정수 값으로 변환
(함수)
(C++11) (C++11)
바이트 문자열을 std::intmax_t 또는 std::uintmax_t 로 변환
(함수)
(C++17)
문자 시퀀스를 정수 또는 부동 소수점 값으로 변환
(함수)
C 문서 참조: atoi , atol , atoll