Search code examples
qt4iostreamcoutconsole-output

QTextStream used for console output


I'm facing this really annoying problem with QTextStream used for console output.

QTextStream cout(stdout, QIODevice::WriteOnly);
cout.setRealNumberPrecision(1);
cout.setPadChar('.');

//  some code generating values of f[i] [...]

for (int i = 10; i >= 0; i--)
{
    if (f[i] < -0.04 || f[i] > 0.04 || 1)
    {
       cout.setRealNumberNotation(QTextStream::FixedNotation);
       cout.setFieldAlignment(QTextStream::AlignRight);
       cout.setFieldWidth(8);
       cout << f[i];
       cout.setFieldAlignment(QTextStream::AlignLeft);
       cout.setFieldWidth(3);
       cout << "*x^";
       cout.setFieldAlignment(QTextStream::AlignLeft);
       cout.setNumberFlags(cout.numberFlags() & ~QTextStream::ForceSign);
       cout << i << endl;
    }
}

The results look like this with the found polynomial is:

.....0.0*x^10.
......-0.0*x^9..
.......0.0*x^8..
......-0.0*x^7..
.......0.0*x^6..
.......1.0*x^5..
.....-36.0*x^4..
.....397.0*x^3..
...-1674.0*x^2..
....2753.0*x^1..
...-1440.0*x^0..
..

I cannot get rid of this strange shift in the first line, and I don't know where .. comes from. I think that there might be some problem with alignment flags, but have no idea what exactly may it is.

Thanks for the help.


Solution

  • If I were to guess, I'd say the endl is being left aligned and padded to 3 characters, with the extra two characters appearing after the return so that they show up at the beginning of the next line. None on the first line and all alone on the last line. Try setting the field width back to 1 before outputting the endl.