'C++' std::stoi, std::stol, std::stoll

토스트·2024년 12월 25일

'C++' std::string

목록 보기
2/12

stoi, stol, stoll

C++11 ~

int stoi(const std::string & str, std::size_t * pos = nullptr, int base = 10);
int stoi(const std::wstring & str, std::size_t * pos = nullptr, int base = 10);

long stol(const std::string & str, std::size_t * pos = nullptr, int base = 10);
long stol(const std::wstring & str, std::size_t * pos = nullptr, int base = 10);

long long stoll(const std::string & str, std::size_t * pos = nullptr, int base = 10);
long long stoll(const std::wstring & str, std::size_t * pos = nullptr, int base = 10);

: 원어로는 'string to int', 'string to long', 'string to long long'이며, 문자열에 있는 부호 있는 정수를 해석하여 반환합니다.
만약 0번째 index가 지정한 진법으로 해석이 불가능하면 해당 함수는 Error를 발생시킵니다.

  • str : 해석하고자 하는 문자열
  • idx : 해석이 불가능한 시작지점
  • base : 문자열을 해석할 때 해석할 진법 (기본값은 10진법으로 변환합니다.)

<example>

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str = "12A5";

	size_t idx;
    
    // 16진법으로 변환
	cout << "Hexadecimal : " << stoi(str, &idx, 16) << endl;
	cout << "Hexadecimal idx : " << idx << endl;
	
    // 2진법으로 변환
	cout << "Binary number : " << stoi(str, &idx, 2) << endl;
	cout << "Binary number idx : " << idx << endl;
	
    // 10진법으로 변환
	cout << "decimal number : " << stoi(str, &idx) << endl;
	cout << "decimal number idx : " << idx << endl;

	return 0;
}

결과값

0개의 댓글