string to float conversion?

前端 未结 9 1831
-上瘾入骨i
-上瘾入骨i 2020-12-18 14:16

I\'m wondering what sort of algorithm could be used to take something like \"4.72\" into a float data type, equal to

float x = 4.72;
相关标签:
9条回答
  • 2020-12-18 14:52

    From cplusplus.com: "stringstream provides an interface to manipulate strings as if they were input/output streams."

    You can initialize a stringstream with your string then read a float from the stringstream using operator>> just like you would with cin.

    Here is an example:

    #include<iostream>
    #include<string>
    #include<sstream>
    using namespace std;
    
    int main() {
      string s = "4.72";
      stringstream sstrm(s);
      float x;
      sstrm >> x;
      cout << x << endl;
    }
    
    0 讨论(0)
  • 2020-12-18 14:54

    I assume you want an actual algorithm, not a library function that already does it. I don't have time to write and test actual code, but here is what I would do:

    1. Initialize a float that will be used as an accumulator to 0.
    2. Figure out where the decimal place is in the string, this will let you know what "column" each of the digits is (i.e. 100s, 10s, 1s, 1/10ths, etc).
    3. Start at the beginning of the string.
    4. Take that digit, convert to an int (trivially done by subtracting 0x30 from the ASCII value)
    5. Multiply the value by the place column (for the first digit in your example, that would be 4 * 1 == 4, for the next digit 7 * 0.1 == 0.7).
    6. Add the result to the accumulator
    7. Repeat from step 4 for each remaining digit.
    8. The accumulator now contains your result.

    Due to the roundoff of converting between base 10 and base 2 in every iteration of this loop, the result you get from this algorithm may not be the closest possible binary representation to the original value. I don't really know of a good way to improve it though... perhaps someone else can chime in with that.

    0 讨论(0)
  • 2020-12-18 15:05

    scanf, operator>> for istreams, and strtof would be the obvious choices.

    There is also atof, but, like atoi, it lacks a way to tell you there was an error in the input, so it's generally best to avoid both.

    0 讨论(0)
提交回复
热议问题