en.cppreference.com/w/cpp/string/basic_string/stol
std::stoi, std::stol, std::stoll - cppreference.com
(1) (since C++11) (2) (since C++11) (3) (since C++11) Interprets a signed integer value in the string str. Discards any whitespace characters (as identified by calling isspace()) until the first non-whitespace character is found, then takes as many charact
en.cppreference.com
C++에서 문자열을 정수형으로 변환해주는 함수 설명을 해드리겠습니다.
int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 )
long stol( const std::string& str, std::size_t* pos = 0, int base = 10 )
long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 )
이렇게 함수마다 반환 값의 형만 다를 뿐 기능은 다 같기에 가장 많이 쓰이는 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 )
1) str : 정수형으로 변환하고 싶은 문자열
※ wstring은 데이터 사이즈가 큰 문자열을 담을 때 사용합니다.(출력도 cout이 아닌 wcout으로 해야하고 "문자열"이 아닌 L"문자열" 이렇게 담깁니다.)
2) pos : 문자열을 정수형으로 바꾸고 바꾼 문자열 바로 앞 character을 가리키게 됩니다. default 값은 nullptr이며 pos를 사용하지 않는다는 뜻 입니다.
3) base : 문자열에 쓰여진 숫자가 어떤 정수형인가를 기입하는 매개변수입니다. 16이면 16진수 2이면 2진수 입니다. 만약 base를 0으로 사용하신다면 동적으로 변환해드려요~
#include<iostream>
#include<string>
using namespace std;
int main() {
string str_dec = "123456, abcdefg";
int dec;
size_t sz;
dec = stoi(str_dec, &sz);
cout << "num : " << dec << " string : " << str_dec.substr(sz) << '\n';
string str_hex = "40c2";
int hex;
hex = stoi(str_hex, nullptr, 16);
cout << str_hex << " : " << hex << '\n';
string str_bin = "11101011";
int bin;
bin = stoi(str_bin, nullptr, 2);
cout << str_bin << " : " << bin << '\n';
string str_oct = "712342";
int oct;
oct = stoi(str_oct, nullptr, 8);
cout << str_oct << " : " << oct << '\n';
string str_auto = "0xfc1";
int auto_num;
auto_num = stoi(str_auto, nullptr, 0);
cout << str_auto << " : " << auto_num << '\n';
return 0;
}
보시면 string 클래스의 내부 함수 substr()을 사용하기 위해서 이런 식으로 사용할 수 있습니다.
이렇게 유용한 stoi 함수를 설명해 드렸는데요 궁금한 점 있으시면 댓글 남겨주세요~
'programming > C 와 C++' 카테고리의 다른 글
<C++> 정수형을 문자열로 (0) | 2020.10.19 |
---|