728x90
반응형
알고리즘 문제를 풀다가 string을 int로 변환해야 하는 경우가 있어서 찾아보고 정리했다. (string -> int) (int -> string)
to_string()
먼저, <string>헤더 파일을 선언해줘야 한다.
상수 값을 string 객체로 변환하는 함수이다.
int 외에도 float, double도 string으로 변환이 가능하다.
#include <iostream>
#include <string>
// int -> string
int n = 30;
string str = to_string(n);
cout << str << endl;
/*실행 결과
30
*/
stoi() 시리즈
먼저, <string>헤더 파일을 선언해줘야 한다.
string 객체를 int로 변환하는 함수이다.
stoi() = string to int
stof() = string to float
stol() = string to long
stod() = string to double
이 함수는 C++11이후에 도입된 함수이다. (modern C++)
#include <iostream>
#include <string>
// int -> string
int n = 30;
string str = to_string(n);
cout << str << endl;
// string -> int
int a = stoi(str);
cout << a << endl;
/*실행 결과
30
30
*/
stringstream
먼저, <sstream>헤더 파일을 선언해줘야 한다.
string 값을 추출하여 int값에 넣는 방식이다.
#include <iostream>
#include <string>
#include <sstream>
stringstream ss;
string str = "26";
int num = 0;
ss << str; // str 변수에서 string 값을 추출
ss >> num; // 추출한 값을 num에 넣음
cout << num << endl;
/*실행 결과
30
*/
728x90
반응형
'📕Programming > 📝Etc' 카테고리의 다른 글
벡터 중복 원소 제거 (0) | 2024.11.12 |
---|---|
소소한 팁 (0) | 2024.05.29 |
ios_base::sync_with_stdio(false), cin.tie(0) 시간초과 해결 (0) | 2024.01.02 |
pragma region 및 endregion (0) | 2023.07.04 |
바이트 저장 순서 (0) | 2023.06.25 |