1

I want to convert string to float. I used the function std::atof, but when i have a string of zero this does not work because the return number of std::atof is 0 if it was succesful. Some of the strings are not numbers. There for, with this code i wrote:

  float att_valur_converted;
        att_valur_converted = std::atof(m_pAttr->att_value);
        if (att_valur_converted != 0.0){      
        sprintf(m_pAttr->att_value,"%.2f", att_valur_converted);

This will not work for zero. What can I do so this will work for zero? Thanks.

Efrat.shp
  • 117
  • 1
  • 9
  • [`strtof`](https://en.cppreference.com/w/cpp/string/byte/strtof), [`istringstream`](https://en.cppreference.com/w/cpp/io/basic_istringstream/basic_istringstream), [`sscanf`](https://en.cppreference.com/w/cpp/io/c/fscanf), ... You should find some duplicates here on SO. – Aconcagua Apr 11 '19 at 11:31
  • "the return number of std::atof is 0 if it was succesful" -> "the return number of std::atof is 0 if it was **not** succesful" – 463035818_is_not_an_ai Apr 11 '19 at 11:36
  • 1
    Use [std::stof](https://en.cppreference.com/w/cpp/string/basic_string/stof), as pointed out in one of the answers in the question this one is marked a duplicate of. – Nikos C. Apr 11 '19 at 11:38

1 Answers1

2

Use std::stod for such operations if you have access to C++11.

Otherwise use std::stringstream as in the following:

double f = 0.0;    
std::stringstream ss;
std::string s = "213.1415";    
ss << s;
ss >> f;  //f now contains the converted string into a double  
cout << f; 

Of course in both cases you have to deal with the fact the such conversion might fail for instance if you try to call stod with "blablabla" as input.

The two methods that I suggested deal with this scenario in two different ways:

  1. stod throws an exception that you can catch
  2. sstream sets a flag that you can query using bool ss.good(). good will return true is the conversion was successful, false otherwise.
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
  • Thanks,I forgot to mention that some of the strings are not numbers. I see std::stod cannot deal with this.. do you know anything else? – Efrat.shp Apr 11 '19 at 11:37
  • 1
    if the string you are passing cannot be converted then stod deals with it by throwing an exception that you can catch. – Davide Spataro Apr 11 '19 at 11:55
  • 1
    It is also recommended to check the status of the extraction, "if(ss.good()) { okToUsef(f) } else { DidNotConvertSo_handleError(); } – 2785528 Apr 11 '19 at 12:07