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

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.

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)

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.