4

我不理解以下表达式中的逻辑,尽管它工作得很好:

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

前面的代码正确输出了我的期望:hello there.

我的逻辑是:

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

但它输出了一些意想不到的东西:hellothere.我的期望是“there”的第一个字符“t”位于输出区域的第 7 列,即 6 列宽度之后。换句话说,我的概念是“left setw(n)”应该表示“从输出区域的第一个列开始的 n 列(空格)”,就像一些带有编号列的数据表单,以便于查找数据。

你能解释一下吗?

4

2 回答 2

5

setwiostreams 操纵器适用于输出的下一个项目,并且仅适用于该项目。所以在第一个片段中,"hello"修改为“left, field width 6”,从而产生以下输出:

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

默认情况下,填充字符是空格 ( ' '),这是在没有更多输入数据且尚未达到字段宽度时输出的内容。

在第二个片段中,只有项目"there."被操作。由于它已经包含六个输出字符,因此操纵器无效。

于 2016-04-20T12:38:12.913 回答
1

操纵器改变ostream. 因此,它们应该在要求流输出某些内容之前应用。

在你的情况下,你问:

  • 格式化下一个输出左侧
  • 格式化下一个输出,大小为 6 个字符
  • 输出“你好”

因此,流输出单词“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)
于 2016-04-20T12:37:54.680 回答