본문 바로가기
C++ 200제/코딩 IT 정보

C++11 stoi stol stoll 함수 사용법, 문자에서 정수 변환 예제

by vicddory 2018. 9. 25.

C++11 stoi stol stoll 함수 사용법, 문자에서 정수 변환 예제


string 헤더 파일에 정의된 함수 원형은 아래와 같습니다.


1
2
3
4
5
6
7
8
int       stoi( const std::string& str, std::size_t* pos = 0int base = 10 );
int       stoi( const std::wstring& str, std::size_t* pos = 0int base = 10 );
 
long      stol( const std::string& str, std::size_t* pos = 0int base = 10 );
long      stol( const std::wstring& str, std::size_t* pos = 0int base = 10 );
 
long long stoll( const std::string& str, std::size_t* pos = 0int base = 10 );
long long stoll( const std::wstring& str, std::size_t* pos = 0int base = 10 );
cs


문자열 string str에서 부호있는 정수를 인식하고 반환합니다. (signed integer)


1
2
3
1std::strtol(str.c_str(), &ptr, base) or std::wcstol(str.c_str(), &ptr, base)
2std::strtol(str.c_str(), &ptr, base) or std::wcstol(str.c_str(), &ptr, base)
3std::strtoll(str.c_str(), &ptr, base) or std::wcstoll(str.c_str(), &ptr, base)
cs


위 함수는 공통으로 isspace()를 이용해 첫 번째 공백을 찾습니다. 그리고 다음번 유효한 숫자를 찾습니다. (base-n, n = base 정수) 이 과정을 반복하며 문자는 버리고 숫자는 합쳐 유효한 정수값을 생성해 반환합니다.


  • 옵션 1 : +, - 기호
  • 옵션 2 : prefix, 진수를 나타내는 부호 (0 또는 8)
  • 옵션 3 : 0x 또는 0x 진수를 나타내는 부호 (0 또는 16)


C++11 stoi stol stoll 함수 사용법, 문자에서 정수 변환하는법[C++ 문자 -> 정수 변환, 추출]

매개변수


  • str : 변환할 문자열
  • pos : 처리된 문자 수를 저장할 정수형 변수
  • base : number base 진수


반환 값


  • 부호있는 정수 유형의 값 (문자열 -> 숫자)


예외 처리


  • std::invalid_argument : 변환을 수행할 수 없는 경우
  • std::out_of_range : 변환된 값이 범위를 벗아날 경우


c++ 11 함수 문자 정수 변환[C++ 문자 -> 정수 변환, 추출]


예제


샘플 소스 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
 
int main()
{
    std::string str1 = "45";
    std::string str2 = "3.14159";
    std::string str3 = "31337 with words";
    std::string str4 = "words and 2";
 
    int myint1 = std::stoi(str1);
    int myint2 = std::stoi(str2);
    int myint3 = std::stoi(str3);
    // error: 'std::invalid_argument'
    // int myint4 = std::stoi(str4);
 
    std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
    std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
    std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
    //std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}
cs


샘플 결과


1
2
3
std::stoi("45") is 45
std::stoi("3.14159") is 3
std::stoi("31337 with words") is 31337
cs


출처 : cppreference

C++11 stoi stol stoll 함수 사용법, 문자에서 정수 변환 예제