IO manipulators manipulate previous cout expressions?

G

Guest

The code:


// Block 1
//
cout << "Integrating " << str << " on [" << low << "," << high
<< "]" << endl << " exact answer: " << exact << endl << flush;

#if 0

// Block 2
//
for (int i = 0; i < 6; ++i )
{
cout << setw(16) << setiosflags(ios::left) << label << flush;
cout << setiosflags(ios::right) << setw(20) << setiosflags(ios::fixed)
<< setprecision(17) << answer;
cout << " error: " << fabs(exact - answer) << endl;
}

#endif


The output looks like:


Integrating x on [0,10]
exact answer: 50


However, when I delete the "#if 0" and "#endif", the output becomes:


Integrating x on [0.00000000000000000,10.00000000000000000]
exact answer: 50.00000000000000000


I tried sticking in a "flush" in Block 1 to make sure the buffer is flushed
and unaffected by the manipulators within Block 2. But it doesn't seem to do
a bit of good.

Why is it that the manipulators in block 2 affect the output generated in
block 1?

Thanks,
Pete
 
A

Andre Kostur

The code:


// Block 1
//
cout << "Integrating " << str << " on [" << low << "," << high
<< "]" << endl << " exact answer: " << exact << endl << flush;

#if 0

// Block 2
//
for (int i = 0; i < 6; ++i )
{
cout << setw(16) << setiosflags(ios::left) << label << flush;
cout << setiosflags(ios::right) << setw(20) << setiosflags(ios::fixed)
<< setprecision(17) << answer;
cout << " error: " << fabs(exact - answer) << endl;
}

#endif


The output looks like:


Integrating x on [0,10]
exact answer: 50


However, when I delete the "#if 0" and "#endif", the output becomes:


Integrating x on [0.00000000000000000,10.00000000000000000]
exact answer: 50.00000000000000000


I tried sticking in a "flush" in Block 1 to make sure the buffer is flushed
and unaffected by the manipulators within Block 2. But it doesn't seem to do
a bit of good.

Why is it that the manipulators in block 2 affect the output generated in
block 1?



Please post a minimal, compilable program which exhibits the problem.
With the short snippet that you've posted, it would seem that your loop
body is never executed... since there is no "error:" output shown.

I'm suspecting that the code snippet that you've shown is executed
multiple times, and that the first time Block 1 is executed, it works as
expected, but the 2nd and subsequent executions are showing the "odd"
behaviour.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top