숫자를 문자열로 바꾸기 (to_string)
숫자를 문자로 바꾸고 싶을 때,
to_string(변수이름) 으로 쉽게 바꿀 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include<iostream>
#include<string>
using namespace std;
int main() {
int n1 = 10;
float n2 = 10.2f;
cout << n1 << endl << n2 << endl<< n1+n2 << endl; // 숫자이므로 더하면 20.2가 나올것
string s1 = to_string(n1); // 10을 문자열로 변경
string s2 = to_string(n2); // 10.2를 문자열로 변경
cout << s1 << endl << s2 << endl << s1+s2 << endl; // 문자이므로 더하면 둘의 문자를 합쳐논 결과가 나올것
return 0;
}
|
cs |
숫자 일 때는 두 수의 합, 문자일 때는 두 문자의 합이 출력 된 것을 확인할 수 있다.
문자열을 숫자로 바꾸기 (stoi, stof)
문자를 숫자로 바꾸고 싶을 때,
stoi(변수이름) => int
stof(변수이름) => float
으로 쉽게 바꿀 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include<iostream>
#include<string>
using namespace std;
int main() {
string s1 ="20";
string s2 = "20.2";
cout << s1 << endl << s2 << endl << s1 + s2 << endl; // 문자이므로 더하면 둘의 문자를 합쳐논 결과가 나올것
int n1 = stoi(s1);
float n2 = stof(s2);
cout << n1 << endl << n2 << endl << n1 + n2 << endl; // 숫자이므로 더하면 40.2가 나올것
return 0;
}
|
cs |