0

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
  • 1
    Use \\n in the input? Effectively, you want to translate the character whose value is \n (value is 10 in ascii) to the characters \ and n. Commented Jul 16, 2021 at 22:26
  • @Justin but that would give 42\n at the final iteration - but I want to have a newline character Commented Jul 16, 2021 at 22:30

2 Answers 2

2

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"
"
"
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.