954,157 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Manipulators

Hi i am trying to understand manipulators. Can someone explain what is happening here

for (int i = 0; i < n; i++) {
        cout << setiosflags(ios::left) << setw(15) << item[i]
             << setw(8) << setprecision(0) << code[i]
             << setiosflags(ios::right) << setw(8) << setprecision(2)
             << setiosflags(ios::fixed | ios::showpoint) << cost[i] 
             << endl;
    }


For the first time, i mean in the first iteration of the loop, it prints correctly but from the second iteration, the output always seems to be right justified. Why?

Here is the output of the above loop

dsjfh          102        32.32
        jdshfjd     120 1212.00
       dfdsfdsf     322   32.23
sweeya
Newbie Poster
8 posts since Nov 2008
Reputation Points: 10
Solved Threads: 1
 

The short answer is that ios::left and ios::right (and some others) are not mutually exclusive, but your code reflects an assumption that they are. It is possible to have both set simultaneously and, of so, it is up to the implementation to decide which one (or a combination) applies.

Try using resetiosflags() manipulators to restore the various flags to their defaults before each line of output.

grumpier
Posting Whiz in Training
211 posts since Aug 2008
Reputation Points: 193
Solved Threads: 32
 

Hi,
Thanks, using resetiosflags worked. I was under the impression that they are mutually exclusive. Anyways, how is it working for the first one correctly?(just want to understand what is happening)

sweeya
Newbie Poster
8 posts since Nov 2008
Reputation Points: 10
Solved Threads: 1
 
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 
Hi, Thanks, using resetiosflags worked. I was under the impression that they are mutually exclusive. Anyways, how is it working for the first one correctly?(just want to understand what is happening)


On the first loop iteration, the stream flags are set to defaults. That is not true for subsequent iterations.

grumpier
Posting Whiz in Training
211 posts since Aug 2008
Reputation Points: 193
Solved Threads: 32
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You