Solved...Converting string to float with sstream issue

The fix was to use
cout << fixed << gained << endl;

I'm using streamstring to convert a string to a float like this... I'm grabbing the number from between " by " and " to " which does work fine in my tests.
1
2
3
4
5
6
7
8
9
10
                        f1 = line.find(" by ") + 4;
                        f2 = line.find(" to ");
                        if(f1 != string::npos && f2 != string::npos)
                        {
                            output.append(line, f1, (f2-f1));
                            stringstream strStream(output);
                            strStream >> gained;
                            cout << gained << endl;
                            //output += " ";
                        }


The issue is anytime a exp gain is smaller then 000100 (ex. 000053) it will make the float = 5.3e-005.
1
2
3
4
5
6
Mind 1.3e-005
Repairing 0.000683
Mind logic 1.5e-005
Miscellaneous items 5.3e-005
Miscellaneous items 5.3e-005
Miscellaneous items 5.3e-005


Actual text file contains...
1
2
3
4
5
6
[11:00:42] Mind increased by 0.000013 to 28.273088
[11:00:44] Repairing increased by 0.000683 to 36.72822
[11:00:45] Mind logic increased by 0.000015 to 33.352554
[11:00:46] Miscellaneous items increased by 0.000053 to 59.788166
[11:00:48] Miscellaneous items increased by 0.000053 to 59.788219
[11:00:49] Miscellaneous items increased by 0.000053 to 59.788273


Edit: I also tried using sprintf..
sprintf((char*)output.c_str(), "%f", gained);
It's output is always like..
1
2
3
Miscellaneous items 8.17609e-027
Repairing 8.17609e-027
Mind logic 8.17609e-027


and...

double gained = ::atof(output.c_str()); This has the same result as sstream
Last edited on
You can use some of the iomanipulators to format your number the way you desire. Look for the setprecison() member function as well as the std::ios format fields.

http://www.cplusplus.com/reference/iomanip/
http://www.cplusplus.com/reference/ios/ios_base/setf/
What exactly is the question?
If we take this line:
[11:00:46] Miscellaneous items increased by 0.000053 to 59.788166
The string output (assuming it is empty at the start), will contain "0.000053"

If that is converted to type double, then 5.3e-05 is a correct representation of the number.

If you prefer not to use scientific notation, then instead of
cout << gained << endl;
use
cout << fixed << gained << endl;
Ah, I should have mentioned I tried doing that aswell but the issue I had was the floats can change alot. x.x, x.xx, x.xxx... all the way to 6 decimals.

Edit: Chervil that did what I was needing... How on earth did you even find out about << fixed... always something little. Thanks a bunch for the replies.
Last edited on
How on earth did you even find out about << fixed

I looked on the reference page here:
http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
Topic archived. No new replies allowed.