string to float exponential notation

I need to convert a string with a float number in exponential notation into a float.

Here are some examples of the numbers.

2.127 -9 1.039 -9 1.632-11
5.6023-1 5.6345-1 5.7487-1
5.578-13 6.996-14 8.280-20
7.007-11 1.961-11 3.648-15
1.9516-2 1.6268-2 3.0845-3
9.4416-2 9.5268-2 9.6445-2
6.3458-7 3.3150-7 6.6691-9
0.0000 0 0.0000 0 5.1529-2
5.1090-2 5.1342-2 0.0000 0

Any suggestions?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{

  stringstream buffer;
  string input = "1.039";
  float output;
  buffer << input;
  buffer >> output;
  cout << "float is " << output << endl;

  buffer.str("" );
  buffer.clear();
  
  input = "1.6268e-2";
  buffer << input;
  buffer >> output;
  cout << "float2 is " << output << endl;
  
}

The problem is my numbers don't have an "e" inside.

I try to find "[0-9]{1}-[0-9]{1}" with boost::regex and change it with boost::regex_replace. But I have trouble how to write the replace string. I don't know the syntax for [first number]e-[second number].

Then I could use your solution.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{

  stringstream buffer;
  string input = "1.039";

  float output;
  buffer << input;
  buffer >> output;
  cout << "float is " << output << endl;

  buffer.str("" );
  buffer.clear();
  
  input = "1.6268-2";
  
  for (int x=0; x<input.size(); x++)
  {
     if (input[x] == '+' || input[x] == '-')
       { input.insert(x,"e"); break;}
  }
 

  buffer << input;
  buffer >> output;
  cout << "float2 is " << output << endl;
  
}

I think this solution would produce an error when the float is a negative number like"-1.2345-10".
I think this solution would produce an error when the float is a negative number like"-1.2345-10".


The solution to that is extremely simple. Replace a 0 with a 1. I'll leave you to work out where.
Topic archived. No new replies allowed.