【问题标题】:Sticky Manipulators C++ 14粘性操纵器 C++ 14
【发布时间】:2018-07-07 00:14:40
【问题描述】:

这个帖子还是真的吗? Which iomanip manipulators are 'sticky'?

据我了解,所有数字操纵器都具有粘性,例如十六进制、八进制、固定、科学。但不是左右。还有其他粘的吗?使用粘性意味着您可以多次使用输出流,而无需再次设置操纵器。

我用这个代码来测试:

std::istringstream test { "Fully !!!weired~ word0s!! cheers" };
std::cout << std::right << std::setw(20) << std::scientific;
while (test.good()) {
    std::string x;
    test >> x;
    std::cout << x << "\n";
}

std::cout  <<  0.1;

输出:

               Fully
!!!weired~
word0s!!
cheers
1.000000e-01

【问题讨论】:

  • 您应该阅读Why is iostream::eof inside a loop condition considered wrong?test.good() 放入循环条件与!test.eof() 相同。
  • 但是我正在检查 .good() - en.cppreference.com/w/cpp/io/basic_ios/good 这不是 !eof() 就像你在表格中看到的那样。
  • @thomas 问问自己如何知道test &gt;&gt; x 何时失败。你不会,直到(a)它确实如此,并且(b)你在那之后立即将垃圾打印到std::cout。只有在 both 发生之后,您才会迭代下一个循环,good() 最终会告诉您轮子掉了。到那时为时已晚。 Read the linked question.
  • 我理解您的评论。是的,例如,如果 x 是 int,则轮子掉了下来,并且流也处于失败状态。我的教授使用这个例子: while (is.good() && !std::isalpha(is.peek())) { is.ignore();带有注释:在条件中使用 is.good(),因为这将阻止使用 peek() 从 EOF 状态的流中读取
  • @thomas 教授很少知道 C++ 足以编写代码。 “在条件中使用 is.good()”是错误的。

标签: c++ string stream manipulators


【解决方案1】:

似乎 setw(20) 的代码中存在错误,这是左右操纵器工作所必需的。这意味着左右也是粘性的。而且我认为这篇文章对于 C++ 14 仍然有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 2014-05-15
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多