Am I using atof wrong?

Hi Everyone, I am attempting to convert a c string to a float number with atof. But for some reason, atof always return an integer, which I really could not figure out why. Below is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <stdio.h>
  #include <stdlib.h>
  #include <string>
  #include <cstring>
  #include <iostream>

  using namespace std;

int main(){
  string double_str = "0.0";
  double d = atof(double_str.c_str());
  cout << "double is: " << d << endl;
 
 return 0;
}


Perhaps I am doing this wrong...but the result is always:

double is: 0

Any ideas?

Thanks.
You are using it correctly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdlib>
#include <string>

int main()
{
    std::string str = "0.0" ;
    double d = std::atof( str.c_str() ) ;
    double e = std::stod(str) ;
    std::cout << d << ' ' << e  << '\n' ; // 0 0

    str = "-12.345" ;
    d = std::atof( str.c_str() ) ;
    e = std::stod(str) ;
    std::cout << d << ' ' << e  << '\n' ; // -12.345 -12.345

    str = "+Infinity" ;
    d = std::atof( str.c_str() ) ;
    e = std::stod(str) ;
    std::cout << d << ' ' << e  << '\n' ; // inf inf
}

http://coliru.stacked-crooked.com/a/22c735f6dda752c2
Topic archived. No new replies allowed.