2014-07-21 49 views

回答

1

可以使用C函數atof,刪除所有「」字符後:

#include <string> 
#include <algorithm> 
#include <stdlib.h> 

double strToDouble(string str) 
{ 
    str.erase(remove(str.begin(), str.end(), ','), str.end()); 
    return atof(str.c_str()); 
} 

它也可以不使用任何C++ 11功能。

0

請檢查了這一點。雖然它很大,但它會爲你的目的 -

string str = "1,234,567.00",temp=""; 
    temp.resize(str.size()); 

    double first = 0.0, sec = 0.0; 

    int i=0; 
    int tempIndex = 0; 

    while(i<str.size() && str[i]!='.') 
    { 
     if(str[i]!=',') 
      temp[tempIndex++]=str[i]; 
     i++; 
    } 

    if(temp.size()>0) 
    { 
     for(int index = 0; index < tempIndex ; index++) 
     { 
      first = first*10.0 + (temp[index]-'0'); 
     } 
    } 

    if(i<str.size()) 
    { 
     double k = 1; 
     i++; // get next number after decimal 
     while(i<str.size()) 
     { 
      if(str[i]==',') 
      { 
       i++; 
       continue; 
      } 
      sec += (str[i]-'0')/(pow(10.0,k)); 
      i++; 
      k++; 
     } 
    } 

    double num = first+sec; 
    if(str[0]=='-') 
    num = (-1.0*num); 
    printf("%lf\n",num); 

我會用這個,而不是使用STL。