C++ converting string to a float

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thatos
    New Member
    • Aug 2007
    • 105

    C++ converting string to a float

    I have this line of code in my program
    Code:
    string line = "1";
    I would like to convert line into a float, now I can't use
    Code:
    float i = atof(line)
    because atof() takes in char * as its argument.
    Does someone know how can I convert a string into a float or at least convert type string to char * then use atof().
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    The string class has a c_str() function that can help you.

    kind regards,

    Jos

    Comment

    • MrPickle
      New Member
      • Jul 2008
      • 100

      #3
      Using the [] operator or at() will also return a char.

      eg;
      string line = "1";
      char c = line[0];

      Or you can use boost's lexical cast. http://www.boost.org/doc/libs/1_39_0...m#lexical_cast

      Or you can use a std::stringstre am

      eg;
      string line = "1";
      stringstream ss(line);
      float f = 0;
      ss >> f;

      Lots of choices (:

      Comment

      Working...