C++ string


string 문자열에 숫자가 들어 있을 때, 이를 int/float/double/long long 등으로 변환할 수 있다.



 종류

 

 stoi

 int

 stoul

 unsigned long

 stoull

 unsigned long long

 stof

 float

 stod

 double

 stold

 long double



사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
 
int main()
{
    std::string str_dec = "2001, A Space Odyssey";
    std::string str_hex = "40c3";
    std::string str_bin = "-10010110001";
    std::string str_auto = "0x7f";
    std::string str_auto2 = "077";
    std::string str_auto3 = "77.5";
    
 
    int i_dec = std::stoi(str_dec);//string의 앞쪽 정수만 int형으로 변환
    int i_hex = std::stoi(str_hex, nullptr, 16); //string 16진수를 10진수로
    int i_bin = std::stoi(str_bin, nullptr, 2);//string 2진수를 10진수로
    int i_auto = std::stoi(str_auto, nullptr, 0);//알아서 변환 string 16진수를 10진수로
    int i_auto2 = std::stoi(str_auto2, nullptr, 0);//string 8진수를 10진수로
    int i_auto3 = std::stoi(str_auto3, nullptr, 0);//string 10진수를 10진수로
 
    std::cout << str_dec << ": " << i_dec << "\n";
    std::cout << str_hex << ": " << i_hex << '\n';
    std::cout << str_bin << ": " << i_bin << '\n';
    std::cout << str_auto << ": " << i_auto << '\n';
    std::cout << str_auto2 << ": " << i_auto2 << '\n';
    std::cout << str_auto3 << ": " << i_auto3 << '\n';
 
    return 0;
}
 
cs


실행 결과


마찬가지로 int/double/flaot 등을 string 으로 변환할 수 있다.


사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
 
int main()
{
    std::string str1;
    std::string str2;
    std::string str3;
    
    int n1 = 100;
    double d1 = 200.5;
    long long n2 = 123456789123456789;
 
    str1 = std::to_string(n1);
    str2 = std::to_string(d1);
    str3 = std::to_string(n2);
 
    std::cout << str1 << "\n";
    std::cout << str2 << "\n";
    std::cout << str3 << "\n";
 
    return 0;
}
 
cs



참조: http://www.cplusplus.com/reference/string/

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL set  (0) 2018.07.22
[STL] C++ STL list  (0) 2018.07.19
[STL] C++ STL deque  (0) 2018.07.19
[STL] C++ STL vector  (0) 2018.07.19

+ Recent posts