📕Programming/📝Etc

string을 int로 변환하기(반대 경우도) [to_string, stoi, stringstream]

주으기 2023. 11. 27. 15:57
728x90
반응형

알고리즘 문제를 풀다가 stringint로 변환해야 하는 경우가 있어서 찾아보고 정리했다. (string -> int) (int -> string)

 

 

to_string()

먼저, <string>헤더 파일을 선언해줘야 한다.

 

상수 값string 객체로 변환하는 함수이다.

 

int 외에도 float, doublestring으로 변환이 가능하다.

#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
반응형