stringstream
라이브러리 사용
#include <iostream>
#include <sstream>
int main()
{
int i = 0;
stringstream ssInt("123");
ssInt >> i;
if (!ssInt.fail())
cout << ssInt.str() << endl;
return 0;
}
stringstream
을 생성해 문자열을 넣고 >>
연산자로 int를 전달
출력하기 전에 fail()
메소드를 사용해서 실제 numeric 타입인지 체크
➡️ 문자열이 int로 변환되지 않는 경우 fail()
이 true
를 리턴
stoi()
사용
#include <iostream>
#include <string>
int main()
{
string s = "123";
int i = stoi(s);
cout << i << endl;
return 0;
}
다른 숫자형으로 변환하기 위한 메소드에는 stol()
, stod()
, stof()
등이 있음