프로그래밍 언어/C++

[C++] string to int, float, double 자료형 / stoi, stol, stoll

ShovelingLife 2024. 9. 23. 19:09

atoi 계열 함수 및 sscanf()

기존 c에서는 str 형식 사용시 다른 자료형 (int, double, float)에 맞도록 읽어오려면, atoi() 및 sscanf()로 형식을 지정해주었으며, 이를 활용한 간단한 예시는 아래와 같다

const char *str = "12345";

// atoi 계열 함수
int x = atoi(str);

// sscanf 사용
int y;
sscanf(str, "%d", &y);

c++에서는 이와 비슷한 방법으로 stoi() 및 타입 캐스팅 그리고, 반복자를 활용하여, 데이터 변환을 할 수 있는데, 그 중에서 stoi() 계열 함수가 있다.

c++에서의 stoi()

c++에서 stoi() 함수는 문자열을 정수 값으로 변환하는데, stoi()는 이름에서 알 수 있듯이 string to int의 줄임말이며, c++ 11에서 추가되었다. stoi() 함수의 원형은 다음과 같다.

stoi(const std::string& str, std::size_t* pos = nullptr, int base = 10);
  • str: 변환해야 하는 문자열
  • position: 문자열(str) 내에서, 변형된 숫자 위치에 대한 식별자.(얼마 만큼의 position 이 해석되었는지 의미한다.)
  • base: str 이 표현된 진법을 의미(기본 10 진법)

아래는 stoi( ) 함수에 대한 간단한 예제

#include <iostream>
#include <string> // stoi string

using namespace std;

int main() {
    string str1 = "12345";
    int x = stoi(str1);
    cout << "value of stoi(st1) is " << x << endl;
}

stoi() 활용

stoi( ) 함수는  + 또는 – 기호, 숫자 앞에 있는 0, 16진수 접두사(0x 또는 0X) 및 공백 문자를 문제 없이 처리할 수 있다. 또한 stoi( ) 함수는 다른 문자가 뒤에 오더라도, 바르게 정수값을 분리해 낼 수 있다.

int main() 
{
    string s1 = "-123";
    string s2 = "123xyz";
    string s3 = "0000123";
    string s4 = "3.14159";

    int num1 = stoi(s1);
    int num2 = stoi(s2);
    int num3 = stoi(s3);
    int num4 = stoi(s4);

    cout << "num1: " << num1 << endl; // -123
    cout << "num2: " << num2 << endl; // 123
    cout << "num3: " << num3 << endl; // 123
    cout << "num4: " << num4;			//3
}

▶ 단, stoi( ) 함수 적용시, 문자열이 다른 문자열이 앞에 있게 되면, invalid_argument 에러를 반환하게 되므로, 주의

 나머지 계열의 함수인 stoi, stol, stoll 의 함수 모두 쓰임새가 비슷하니 참고 https://en.cppreference.com/w/cpp/string/basic_string/stol

 

pos을 활용한 코드

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

/* 연산자와 피연산자를 분리하는 예제 */
int main() {
	string ss{"123 + 456 + 789 + 10"};
	ss.erase(remove(begin(ss), end(ss), ' '), end(ss));
	cout << ss << endl; // "123+456+789+10";

	vector<char> ops{};
	vector<int> operands{};
	size_t index{};
	operands.push_back(stod(ss,&index));
	
	while(true) {
		ops.push_back(ss[index++]);
		size_t sub_index{};
		operands.push_back(stod(ss.substr(index), &sub_index));
		index += sub_index;
		if(index == ss.size()) break;
	}

	// 123 456 789 10
	copy(begin(operands), end(operands), ostream_iterator<int>(cout, " "));
	
	return 0;
}

 

https://guru.tistory.com/121?category=1038889