Jacob Macallan
Jacob Macallan

Reputation: 979

Using cin to append to a string C++

is there a way to use std::cin to append to a string instead of replacing what's inside?

Or is there a better alternative?

Upvotes: 3

Views: 2804

Answers (1)

fghj
fghj

Reputation: 9394

You can try something like this:

#include <iostream>
#include <iterator>
#include <string>

int main()
{
    std::istream_iterator<std::string> it(std::cin);
    std::istream_iterator<std::string> end_it;
    std::string str;
    for (int i = 0; i < 3; ++i)
        if (it != end_it) {
            str += *it;
            if (i != 2)
                ++it;
        } else {
            break;
        }
    std::cout << "Res: " << str << "\n";
}

but much simpler to use just two std::string variables, one for current input, another for accumulation.

Upvotes: 1

Related Questions