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;
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;
}
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:
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.
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.