2011-01-16 3 views
0

"2.12e-6"과 같은 문자열을 double로 변환 할 수있는 C++ 내장 함수가 있습니까?"2.12e-6"과 같은 문자열을 double로 변환

+0

Windows에서 sscanf 시도 – ThomasMcLeod

+0

"내장"이란 무엇입니까? 표준 런타임 라이브러리에서? – ThomasMcLeod

+2

'atof'라는 질문에 태그를 달았습니다 - atof가 올바른 함수가 아니라고 생각하는 이유가 있습니까? 극단적 인 간결함을 위해서 +1 – Gabe

답변

3

atof가 작업을 수행해야합니다. This 입력이 같이 방법 : 물론

#include <iostream> 
#include <sstream> 
#include <string> 
#include <iterator> 
#include <boost/lexical_cast.hpp> 

int main() 
{ 
    std::string  val = "2.12e-6"; 
    double   x; 

    // convert a string into a double 
    std::stringstream sval(val); 
    sval >> x; 

    // Print the value just to make sure: 
    std::cout << x << "\n"; 

    double y = boost::lexical_cast<double>(val); 
    std::cout << y << "\n"; 
} 

부스트가있다 : 당신이 아니라 다른 모든 종류의 같은
사용 스트림 (대신 교류 기능의) C++ 방법을 사용하는 경우

A valid floating point number for atof is formed by a succession of: 

An optional plus or minus sign 
A sequence of digits, optionally containing a decimal-point character 
An optional exponent part, which itself consists on an 'e' or 'E' character followed by an optional sign and a sequence of digits. 
7
+0

+1. – EmeryBerger

+1

은 최소한의 문자를 만들기 위해 링크를 삽입해야했습니다! –

1

편리한 짧은 커팅 부스트 :: lexical_cast <double> 또는 직접 작성하는 것은 쉽지 않습니다.

+0

효과적인 방법이지만 그는 내장이라고 말했습니다. –

+0

@Charles : 그 이유는 boost :: lexical_cast <>가 마지막입니다 (대안으로 (석조 물처럼 작동하지 않는 상태로 작업해야 함)). 표준 스트림 항목은 내장되어 있지만 lexical_cast <>의 사용자 자신의 버전을 작성하는 것은 하위 재생입니다. –

+0

"돌을 좋아한다"는 것은 무엇을 의미합니까? 영국의 관용구인가요? – Gabe