PDA

View Full Version : How to use QTextStream to replace std::ostringstream



edmhourigan
28th November 2020, 15:06
I have the following code that I am trying to add a double number to a QLabel that must have the following format MMM.NN , this a number less than 100.0 should have a leading 0




double _Heading = 35.5;

QString _TextForDisplay;
QTextStream _Stream(&_TextForDisplay);
_Stream.setRealNumberNotation(QTextStream::FixedNo tation);
_Stream.setRealNumberPrecision(2);
_Stream.setFieldAlignment(QTextStream::AlignRight) ;
_Stream.setPadChar('0');

_Stream << "HDG: " << QTextStream::ForcePoint << _Heading;

QString _qs = *(lcStream.string());
std::cout << "_Stream: " << _qs.toUtf8().constData() << std::endl;


But I get

"_Stream : 235.50" not "035.50".

??? Where is the leading "2" coming from???

>>

Note that using std::ostringstream produces the expected results:



std::ostringstream _TextStream;
_TextStream << "HDG: " << std::dec << std::fixed << std::setprecision(2) << _Heading;
std::cout << lcTextStream.str() << std::endl;


"035.50"

Thanks.

d_stranz
28th November 2020, 18:00
In line 12, you are retrieving the contents of a variable named "lcStream", which is not the same variable as "_Stream".

edmhourigan
29th November 2020, 13:03
That's simply typo on line 12. Thanks.

Added after 5 minutes:

Corrected:
--------------



double _Heading = 35.5;

QString _TextForDisplay;
QTextStream _Stream(&_TextForDisplay);
_Stream.setRealNumberNotation(QTextStream::FixedNo tation);
_Stream.setRealNumberPrecision(2);
_Stream.setFieldAlignment(QTextStream::AlignRight) ;
_Stream.setPadChar('0');

_Stream << "HDG: " << QTextStream::ForcePoint << _Heading;

QString _qs = *(_Stream.string());
std::cout << "_Stream: " << _qs.toUtf8().constData() << std::endl;



Is the '2' prefix coming from the call on line 6?


_Stream.setRealNumberPrecision(2);


If so, that seems like a bug in QTextStream, right?

Added after 14 minutes:

The problem was caused by adding this:
'<< QTextStream::ForcePoint'

ForcePoint operator forces comma separators, not decimal point (poorly named operator, IMHO).


Changing to


_Stream << "HDG: " << _Heading;


Fixes the leading '2' digit.

>>> IS THIS A BUG in QTextStream ??? <<<

ChristianEhrlicher
29th November 2020, 17:57
Why should this be a bug? Out tell QTextStream to output 'QTextStream::ForcePoint' which is 2. What you want is QTextStream::forcePoint().