Replace the ...e... in scientific notation

I need the numbers in my output to be compatible with Mathematica and to this end to replace ...e... with ...*10^... . Is there a convenient way to do so, e.g. to access the coefficient and the exponent seperately as the real and imaginary part in complex? My only Ideas so far are

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main(){
  double a=1.23e+45;
  stringstream ss;
  ss<<a;
  string s=ss.str();
  int i=s.find("e");
  if(i>0) s.replace(i,1,"*10^");
  cout<<s<<endl;
  return 0;
}


and

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;
int main(){
  double a=1.23e+45;
  double coeff=a;
  int e=0;
  while(coeff>10){
    coeff/=10;
    e++;
  }
  while(coeff<1){
    coeff*=10;
    e--;
  }
  cout<<coeff<<"*10^"<<e<<endl;
  return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <limits>
#include <complex>
#include <cmath>

std::string mathematica_str( double d )
{
    if( std::isnan(d) ) return "NaN" ;
    else if( std::isinf(d) ) return d < 0 ? "-Inf" : "+Inf" ;

    std::ostringstream stm ;
    stm << std::scientific << std::showpoint
        << std::setprecision( std::numeric_limits<double>::digits10 ) << d ;
        
    std::string str = stm.str() ;
    const auto epos = str.find('e') ;
    return str.substr( 0, epos ) + " * 10^" + str.substr(epos+1) ;
}

std::string mathematica_str( std::complex<double> c )
{ return mathematica_str( c.real() ) + "  +  " + mathematica_str( c.imag() ) + " I" ; }

http://coliru.stacked-crooked.com/a/78020f8d290f3132
Thanks a lot!
This is like my first solution with additional features; it however confirms my guess that there is no C++ routine to display the coefficient and exponent separately. I'll wait a little more whether somebody has a shorter solution before marking the thread as solved.
> there is no C++ routine to display the coefficient and exponent separately.

std::frexp() - normalized fraction and an integral power of two
http://en.cppreference.com/w/cpp/numeric/math/frexp
Thanks for the information. Then I'll do it how you suggested.
Topic archived. No new replies allowed.