Problems writing data to ANSI files using C++ stream functions

  ansi, c++, stream

I am dumping data from an automated experiment to ANSI text files using custom C++ code. In order to facilitate parsing of the files using random reads, I’m trying to establish a standard field width for the values (one per line with a NL following), but the C++ standard library stream functions are making life a bit tricky.

My first attempt was to do output to the file as follows:

ofstream logstream ; .. etc. etc.
…………..
logstream << setw(6) << setfill('0') << left << setprecision(5) << DataValue << "n";

I found rogue entries in the resultant output. All the values to be written are around 50, and what I’m seeing is this <*** NOTE: The webpage formatter is modifying what I’m entering, the 6 values shown below are one per line>

49.935
49.989
500000
50.021
50.123

The third number raw is actually something like 50.000001 – ie. 50 exactly within the setprecision that I’ve set – and the library routines present it as simply ‘50’ – without a DP. The fill then appends the zeroes, resulting in the erroneous value. If I increase the precision, the field width that I set is overridden so I get a violation of the text field length.

My next attempt is to write the values to a stringstream, and handle the formatting myself, which surely shouldn’t be necessary. Is anyone aware of a neat solution?

Source: Windows Questions C++

LEAVE A COMMENT