본문 바로가기
C++ 200제/코딩 IT 정보

C++11 std::string to int 변경할 땐 stoi atoi 함수 사용

by vicddory 2018. 10. 25.
반응형

C++11 std::string to int 변경할 땐 stoi atoi 함수 사용


C++11 부터 std::string을 숫자로 변환하는 함수가 추가되었습니다. 기존에는 아래처럼 문자열을 숫자로 바꿨죠.


1
atoi(str.c_str())
cs


이제는 새로 추가된 함수 stoi를 사용하면 됩니다.


1
std::stoi(str)
cs


위 소스 코드의 str 자리에 std::string 변수를 추가하면 됩니다. 또한 실수형으로도 변환이 가능합니다.


  • long stol(string)
  • float stof(string)
  • double stod(string)


관련 함수는 cpp 레퍼런스 stoi 항목에 자세하게 설명되어 있으며, 별도로 정리한 포스트는 9월에 남겼습니다.


만약 C++11을 사용할 수 없는 환경이라면 아래 5개 코드로 string to int 구현이 가능합니다.




c++ 문자열 정수 변환 stoi[string int 변환 프로그래밍 소스 예제]

 sscanf()


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdio>
#include <string>
 
int i;
float f;
double d;
std::string str;
 
// string -> integer
if(sscanf(str.c_str(), "%d"&i) != 1)
    // error management
 
// string -> float
if(sscanf(str.c_str(), "%f"&f) != 1)
    // error management
 
// string -> double 
if(sscanf(str.c_str(), "%lf"&d) != 1)
    // error management
cs


 std::sto*()


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
 
int i;
float f;
double d;
std::string str;
 
try {
    // string -> integer
    int i = std::stoi(s);
 
    // string -> float
    float f = std::stof(s);
 
    // string -> double 
    double d = std::stod(s);
catch (...) {
    // error management
}
cs


 sstreams


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <sstream>
 
int i;
float f;
double d;
std::string str;
 
// string -> integer
std::istringstream ( str ) >> i;
 
// string -> float
std::istringstream ( str ) >> f;
 
// string -> double 
std::istringstream ( str ) >> d;
 
// error management ??
cs


 Boost's lexical_cast


1
2
3
4
5
6
7
8
9
10
11
12
#include <boost/lexical_cast.hpp>
#include <string>
 
std::string str;
 
try {
    int i = boost::lexical_cast<int>( str.c_str());
    float f = boost::lexical_cast<int>( str.c_str());
    double d = boost::lexical_cast<int>( str.c_str());
catch( boost::bad_lexical_cast const& ) {
    // Error management
}
cs


 Qt


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <QString>
#include <string>
 
bool ok;
std::string;
 
int i = QString::fromStdString(str).toInt(&ok);
 
if (!ok)
    // Error management
 
float f = QString::fromStdString(str).toFloat(&ok);
 
if (!ok)
    // Error management 
 
double d = QString::fromStdString(str).toDouble(&ok);
 
if (!ok)
    // Error management
cs




C++11 stdstring to int 변경할 땐 stoi atoi 함수 사용[string int 변환 프로그래밍 소스 예제]


string int 변환 추천


int tmp = std::stoi(std::string);


문자열을 숫자로 바꾸는 방법에는 여러 가지가 있습니다. c++11에서 지원하는 stoi를 최우선으로 사용하되 환경에 따라 적절히 구현하면 됩니다.


 C++11 std::string to int 변경할 땐 stoi atoi 함수 사용

반응형