How to put multiple inputs in one variable C++

I’m rather new to C++ and don’t really know much about it. I want a solution where the user could type in something like this (on separate lines):

AAA
BBB
CCC

And store it in a variable like this:

AAABBBCCC

Each of the lines in the input are a separate cin. There is only one variable that will store all of this. Is it possible?

>Solution :

Did you mean that 1 variable will store the result, or use just 1 variable throughout the whole program? If you meant the first one, given your inputs res will have AAABBBCCC at the end of the run:

std::string tmp;
std::string res;
for (int i = 0; i < 3; i ++) {
    std::cin >> tmp;
    res += tmp;
}
std::cout << res << std::endl;

You can just write res += tmp because std::string overloads the operator +=.

Leave a Reply