2012-01-07 2 views
0

나는이 수업이 있습니다 문자열을 숫자 형식으로 변환하는 일반적인 방법은 무엇입니까?

template<typename T> class Parser 
{ 
    public: 
     Parser() : count(0) {} 
     virtual void parse(const string&); 
     void get_token(void); 
    private: 
     T result; 
     char token; 
     string expression; 
     int count; 
}; 

이제 클래스, 제네릭하고 내가 숫자를 감지하는이 방법을 사용하는 것, 되었습니까 result이 말하는 double 없었했다. result 이후

while((strchr("1234567890.",token)) 
{ 
    /* add token to a "temp" string */ 
    /* etc. etc. */ 
} 

result = atof(temp.c_str()); 

그러나 제네릭, 내가 atofatoi 같은 어떤 방법을 사용할 수 없습니다 등

어떻게해야합니까?

#include <boost/lexical_cast.hpp> 

void Parser<T>::get_token() { 
    std::string token = ...; 
    result = boost::lexical_cast<T>(token); 
} 

추가 예외 처리 필요 :

+0

¤'std :: istringstream'을 사용할 수 있습니다. 또는 내부적으로 스트림을 사용하는'boost :: lexical_cast'를 사용할 수 있습니다. 건배 & hth., –

+0

@ Xeo : 거의. 그래도 관련이 있습니다. –

+0

@ Lightness : 예, 다시 읽은 후, "일반적인"부분을 놓친 것으로 나타났습니다. – Xeo

답변

6

부스트가 내장 된이 기능이 있습니다.


또는 아마도 당신이 어떤 이유로 부스트를 사용하지 않으 :

void Parser<T>::get_token() { 
    std::string token = ...; 

    std::stringstream ss; 
    ss << token; 
    ss >> result; 
} 

확인 필요 ss의 오류 상태. 그것은 단지 int 구체적으로 설명하지만


더 광대 한 답변은 this related question에서 찾을 수 있습니다.

+0

+1, 감사합니다. 차라리 내 프로젝트를 향상시키지 말고,'stringstream'을 사용하겠습니다. – ApprenticeHacker

+0

@IntermediateHacker : 헤더 만 있으면됩니다. 그게 전부 야. 'boost' 솔루션은 훨씬 강력합니다. 다시 한번 생각해보십시오. –

+0

(파서를 쓰고 있다면, 이미 부스트를 사용하고 있지 않다는 것을 당황스럽게 생각합니다!) –

1

다른 일반적인 템플릿 기반의 Numeric To String 변환기. intdouble 초가 소요됩니다.

#include <sstream> 
#include <iostream> 
#include <string> 
using namespace std; 

template <class T> 
inline std::string Numeric_To_String (const T& t) 
{ 
    std::stringstream ss; 
    ss << t; 
return ss.str(); 
} 


int main(int argc, char *argv[]) 
{ 
    int i = 9; 
    double d = 1.2345; 
    string s; 

    cout <<"Generic Numeric_To_String(anyDatatype) \n\n"; 

    s = Numeric_To_String(i); 
    cout <<"int i to string : "<< s <<" "<< endl; 

    s = Numeric_To_String(d); 
    cout <<"double d to string : "<< s <<" "<< endl; 
    cout <<" \n"; 

    return 0; 
} 
0

당신은 단지 당신이 구문 분석 할 유형의 전체 손이있는 경우 , 당신은 템플릿 특수화 사용할 수 있습니다 : 당신이 필요로하는 모든 convertion을 구현하는 경우

template<> 
void Parser<int>::parse(const string&) 
{ 
    result = atoi(string.c_str()); 
} 

template<> 
void Parser<float>::parse(const string&) 
{ 
    result = atof(string.c_str()); 
} 

... 하지만이 단지 작품을, 당연하지.

+0

atoi 및 atof 관련 - http://stackoverflow.com/questions/2892951/list-of-deprecated-c-functions. 또한 _named_ 매개 변수를 사용해야합니다. 'string.c_str()'이 작동하지 않습니다. –

관련 문제