Ahmed Saleh - 2 months ago 6

C++ Question

I'm trying to write a CSV file, and I have a value which is 6.49483e-005, that's written correctly in the CSV, but it doesn't display correctly in the excel. it reads as 6,48E+00.

I'm doing that in C++, if you want, you can ask for code, I'm using long double for the value that is written to the CSV and then convert it to string, then write it.

`s = "00043E61"`

digitstring = "00000000000001000011111001100001"

sum = 6.4753228798508644e-005

n = 278113

in CVS it's

`6.49483e-005`

in excel :

`stringstream ss;`

ss << hex << s;

unsigned n;

ss >> n;

bitset<32> b(n);

string digitstring = b.to_string();

if(digitstring[0] == '1')

{

negative = true;

}

long double sum = 0;

int exp = 1;

int v = 0;

if(negative)

{

v = 1;

}

else

{

v = 0;

}

for(; v < digitstring.size(); v++)

{

int b = digitstring[v] - '0';

long double result = (long double)b/power(2,exp);

sum+=result;

exp = exp +1;

}

if(negative)

{

sum*=-1;

}

ostringstream os;

os << sum;

resultsSoil.push_back(os.str());

}

Answer

As @ThomasMatthews pointed out, your locale doesn't use `.`

as a digit separator. Therefore, you need to format your numbers the way Excel is expecting them. Plus, commas in a CSV file need to be enclosed in double-quotes. Format your numbers as `"6,49483e-005"`

before you output them to the CSV and you should be OK!