Order iostreams manipulator

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

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 he outputs something unexpected: hellothere.My expectation is that the first character “t” “there” is in the 7th column on the output area, which is after the width of the columns 6. In other words, my concept is that “ left setw (n) "should mean" n columns (spaces) from the first in the output area ", like some data forms with numbered columns for easy data retrieval.

Could you explain?

+4
source share
2 answers

setw iostreams , , . , "hello" ", 6" , , :

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

(' '), , , .

"there.". , .

+5

ostream. , - .

:

  • 6
  • output 'hello'

, "hello", 1 , 6, .

:

std::left + operator <<:

if (os.flags() ios_base:: adjustfield) == ios_base:: left, os.width() - str.size() os.fill()

std::setw:

The width property of the stream will be reset to zero (meaning "unspecified") if any of the following functions are called:

Input
   operator>>(basic_istream&, basic_string&)
   operator>>(basic_ostream&, char*)

Output
  Overloads 1-7 of basic_ostream::operator<<() (at Stage 3 of num_put::put())
  operator<<(basic_ostream&, char) and operator<<(basic_ostream&, char*)
  operator<<(basic_ostream&, basic_string&)
  std::put_money (inside money_put::put())
  std::quoted (when used with an output stream)
+1

All Articles