Home > OS >  How to put multiple inputs in one variable C
How to put multiple inputs in one variable C

Time:06-13

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?

CodePudding user response:

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 =.

CodePudding user response:

If you want user to enter the strings interactively, or if you want to read the strings from a file, then you can use the below method

#include <iostream>
#include <vector>
#include <numeric>

int main()
{
    std::vector<std::string> v;
    std::string s;
    // Enter Ctrl-Z to terminate
    while(std::cin >> s) {
        v.push_back(s);
    }
    auto all = std::accumulate(v.begin(), v.end(), std::string(""));
    std::cout << all << std::endl;
}
AAAA
DDDD
BBBB
CCCC
^Z
AAAADDDDBBBBCCCC

std::accumulate takes a binary predicate as its last argument. If you wish to add a separator between strings you can take advantage of this.

// define a delimiter
std::string delim{"-"};

// lambda to concatenate string with a separator
auto addDelimiter = [=](const std::string& s1, const std::string& s2) {
    std::string result{s1};
    if(!s1.empty() && !s2.empty())
        result  = delim;
    result  = s2;
    return result;
};

auto all2 = std::accumulate(v.begin(), v.end(), std::string(""), addDelimiter);
    std::cout << all2 << std::endl;
AAAA
BBBB
CCCC
DDDD
^Z
AAAA-BBBB-CCCC-DDDD
  • Related