모두의 코드
C++ 레퍼런스 - string 의 stoi, stol, stoll 함수
std::stoi, std::stol, std::stoll
<string> 에 정의됨
// stoi 함수 int stoi(const std::string& str, std::size_t* pos = 0, int base = 10); int stoi(const std::wstring& str, std::size_t* pos = 0, int base = 10); // stol 함수 long stol(const std::string& str, std::size_t* pos = 0, int base = 10); long stol(const std::wstring& str, std::size_t* pos = 0, int base = 10); // stoll 함수 long long stoll(const std::string& str, std::size_t* pos = 0, int base = 10); long long stoll(const std::wstring& str, std::size_t* pos = 0, int base = 10);
string 혹은 wstring 문자열 str 을 base
진법을 사용하는 부호 있는 정수로 변환한 값을 리턴한다. 이 때, 변환 과정에서 문자를 읽었는지는 pos
에 저장된다.
이 때 문자열을 정수로 해석할 때 다음의 과정에 따라 해석을 합니다. 먼저 맨 앞에 붙어 있는 공백 문자들 (isspace()
호출 시 true
인 애들) 을 공백 문자가 아닌 문자가 나올 때 까지 무시 합니다. 그 다음에, 입력 받은 문자열이 base
진법이라 써진 것이라 가정 한 후 읽어들이게 됩니다.
이 때, 정수 문자열의 형태는 아래의 요소들을 포함할 수 있습니다.
부호 (맨 앞에 + 또는 -)
8 진법임을 알려주는 접두사 0 (이 때
base
가 8 이나 0 으로 지정할 때만 해석된다)16 진법을 알려주는 접두사
0x
(이 때base
가 16 이나 0 으로 지정할 때만 해석된다)
이 때 base
로 가능한 값은 0,2,3, ..., 36
이다. 예를 들어서 base
가 2 라면 문자열에 오는 숫자로 가능한 것은 0 과 1 이고, base
가 3 이면 문자열에는 0, 1, 2
만 가능하다. 36
진법을 사용할 경우, 0, 1, 2, ..., 9, a, b, ..., z
까지 총 36
개의 숫자를 이용할 수 있다.
만약에 base
로 0 을 지정한다면, 문자열의 진법이 다음과 같이 결정된다. 맨 앞의 문자가 0 이면 8 진법으로, 0x
이면 16 진법으로, 그 외의 경우 그냥 10 진법 수로 생각된다. 따라서 C++ 에서 사용하는 임의의 정수 리터럴은 base
를 0 으로 지정함으로써 해석할 수 있다.
pos
에 nullptr
을 전달하면 몇 개 문자를 읽었는지 저장하지 않는다. 그 외의 경우에는 str 에서 변환 시에 문자를 몇 개 까지 읽었는지 저장하게 된다.
인자들
str : 변환할 문자열
pos
: 문자열에서 문자 몇 개를 읽어들였는지 저장할 위치base
: 정수 변환 시에 사용할 진법
리턴값
변환된 부호 있는 정수를 리턴한다.
예외
변환이 불가능 할 시,
std::invalid_argument
를 던진다.변환한 값이 정수 범위를 초과 한다면
std::out_or_range
를 던진다.
실행 예제
#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); // 아래의 경우 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::stoi("45") is 45 std::stoi("3.14159") is 3 std::stoi("31337 with words") is 31337
참고 자료
stoul
,stoull
: 문자열을 부호 없는 정수로 바꾼다.stof
,stod
,stold
: 문자열을 부동 소수점 값으로 바꾼다.to_string
: 정수나 부동 소수점 값을 문자열로 바꾼다.

댓글을 불러오는 중입니다..