【问题标题】:c++ : istream_iterator skip spaces but not newlinec ++:istream_iterator跳过空格但不换行
【发布时间】:2021-07-16 22:23:16
【问题描述】:

假设我有

istringstream input("x = 42\n"s);

我想使用 std::istream_iterator<std::string> 迭代这个流

int main() {
    std::istringstream input("x = 42\n");
    std::istream_iterator<std::string> iter(input);

    for (; iter != std::istream_iterator<std::string>(); iter++) {
        std::cout << *iter << std::endl;
    }
}

我按预期得到以下输出:

x
=
42

是否可以有相同的迭代跳过空格但没有换行符?所以我想拥有

x
=
42
\n

【问题讨论】:

  • 在输入中使用\\n?实际上,您希望将值为\n(ascii 中值为10)的字符转换为字符\n
  • @Justin 但这会在最后一次迭代中给出 42\n - 但我想要一个换行符

标签: c++ istream-iterator


【解决方案1】:

std::istream_iterator 并不是真正适合这项工作的工具,因为它不允许您指定要使用的分隔符。相反,请使用std::getline,它确实如此。然后手动检查换行符并在找到时将其删除:

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::istringstream input("x = 42\n");
    std::string s;
    while (getline (input, s, ' '))
    {
        bool have_newline = !s.empty () && s.back () == '\n';
        if (have_newline)
            s.pop_back ();
        std::cout << "\"" << s << "\"" << std::endl;
        if (have_newline)
            std::cout << "\"\n\"" << std::endl;
    }
}

输出:

"x"
"="
"42"
"
"

【讨论】:

    【解决方案2】:

    如果你可以使用 boost 使用这个:

    boost::algorithm::split_regex(cont, str, boost::regex("\s"));
    

    其中“cont”可以是结果容器,“str”是您的输入字符串。

    https://www.boost.org/doc/libs/1_76_0/doc/html/boost/algorithm/split_regex.html

    【讨论】:

      猜你喜欢
      • 2015-02-12
      • 2013-12-18
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      相关资源
      最近更新 更多