문자열을 정수, 실수로 변환하기
문자열을 정수나 실수로 변환하는 과정에는 여러가지가 있습니다.
C 언어에서 <cstdlib>
헤더의 std::atoi()
나 std::atof()
함수를 사용하는 방법, <string>
헤더의 std::stoi()
나 std::stof()
함수를 사용하는 방법,
그리고 std::stringstream
을 사용하는 방법이 있습니다.
atoi()와 atof()
C 언어에서는 atoi()
와 atof()
함수를 사용하여 문자열을 정수와 실수로 변환할 수 있는 함수로 ”ASCII to Integer”의 약자입니다.
이 함수들은 <cstdlib>
헤더에 정의되어 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
const char* num1 = "123";
const char* num2 = "3.141592";
int num = atoi(num1);
float fnum = atof(num2);
printf("num1: %d\n", num);
printf("num2: %f\n", fnum);
}
std::stoi()와 std::stof()
std::stoi()
와 std::stof()
는 “String to Integer”의 약자로, <string>
헤더에 정의되어 있는 함수입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;
int main()
{
string num1 = "123";
string num2 = "3.141592";
int num = stoi(num1);
float fnum = stof(num2);
cout << "num1: " << num << '\n';
cout << "num2: " << fnum << '\n';
}
std::stringstream 클래스와 연산자 오버로딩
std::stringstream
클래스를 사용하면 문자열을 숫자로 변환하는데 사용할 수 있습니다.
문자열 스트림에 해당 문자열을 입력하고, 연산자 오버로딩을 이용해 필요한 타입으로 변환할 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string num1 = "123";
string num2 = "3.141592";
stringstream intSS(num1);
stringstream floatSS(num2);
int inum;
float fnum;
intSS >> inum;
floatSS >> fnum;
cout << "num1: " << inum << '\n';
cout << "num2: " << fnum << '\n';
}
참조
이 기사는 저작권자의 CC BY-NC-ND 4.0 라이센스를 따릅니다.