Search code examples
c++iostreammanipulators

iostreams manipulator order


I do not understand logic in following expression, although it works perfectly:

cout << left << setw(6) << "hello" << "there." ; 

The previous code correctly outputs what I expect: hello there.

My logic is:

cout << "hello" << left << setw(6) << "there."; 

But it outputs something unexpected: hellothere. My expectation is that first character "t" of "there" be at 7th column on output area that is after 6 columns width. In other words my concept is that "left setw(n)" should mean "n columns (spaces) from first one on output area", like some data forms with numbered columns for easy find data.

Could you please explain?


Solution

  • The setw iostreams manipulator applies to the next item that is output, and to that item only. So in the first snippet, "hello" is modified with "left, field width 6", and thus produces the following output:

    |h|e|l|l|o| |
    

    The filler character by default is the space (' '), which is what's output when there is no more input data and the field width hasn't been reached yet.

    In the second snippet, only the item "there." is manipulated. Since it already consists of six output characters, the manipulators have no effect.