int main() { std::istri" /> int main() { std::istri" /> int main() { std::istri"/>

c++ : istream_iterator skip spaces but not newline

328 views Asked by At

Suppose I have

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

I'd like to iterate over this stream using 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;
    }
}

I get the following output as expected:

x
=
42

Is it possible to have the same iteration skipping spaces but not a newline symbol? So I'd like to have

x
=
42
\n
2

There are 2 answers

0
Paul Sanders On

std::istream_iterator isn't really the right tool for this job, because it doesn't let you specify the delimiter character to use. Instead, use std::getline, which does. Then check for the newline manually and strip it off if found:

#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;
    }
}

Output:

"x"
"="
"42"
"
"
0
bakaDev On

If you can use boost use this:

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

where "cont" can be the result container and "str" is your input string.

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