0

I have a code that looks like the following

#include <iostream>
#include <sstream>
using namespace std;
int main(){
    string s = "-1.42-14";
    stringstream ss;
    ss << s;
    double a ;
    ss >> a;
    cout << "a = " << a << endl;
}

I run this code and I get a = -1.42,but I want a = -1.42e-14. what should I do

Max
  • 1

1 Answers1

0

You can simply read in both parts separately and combine them manually:

std::string s = "-1.42-14";
std::istringstream ss(s);

double mantissa;
ss >> mantissa;

double exponent;
ss >> exponent;

double a = mantissa * std::pow(10.0, exponent);

std::cout << "a = " << a << '\n';

Output:

a = -1.42e-14

Note: Given that floating point types are only an approximation of real numbers, when you perform the same calculation by different means, you often arrive at a slightly different value.

Galik
  • 47,303
  • 4
  • 80
  • 117