c ++:istream_iterator跳过空格但不换行

问题描述

假设我有

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

解决方法

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"
"
"
,

如果您可以使用 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