Unknown number of strings (in letters) in the input

Viewed 151

I want to write a program in which the names of n different chemical elements are read in the same line in the input (where 1 ≤ n ≤ 17 and n is also read in the input) (the names are made apart by a space). The names of the chemical elements should be stored in different strings for further uses.

As n is unknown, I don't know how to make something like an "array of strings". Of course I should not make 17 different strings st1,st2,st3,... :D.

Can you please help me? Any help will be high appreciated and they will help me a lot.

Thank you in advance.

1 Answers

It sounds like you want to read in a line and split it with spaces. Try something such as this:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int main()
{
    std::string input;
    std::getline(std::cin, input); // takes one line, stops when enter is pressed
    std::stringstream ss(input); // makes a stream using the string
    std::vector<std::string> strings;
    while (ss >> input) { // while there's data left in the stream, store it in a new string and add it to the vector of strings
        strings.push_back(input);
    }

    for (std::string s : strings) {
        std::cout << "string: " << s << std::endl;
    }
}

You give input such as H He Li, terminated by hitting enter, and the strings are stored in strings (printed in last loop for demonstration).

Edit:

I now see that you want to read the number n in the input, too. In this case, you don't need the stringstream solution. You can do this instead:

int main()
{
    int amount;         
    std::cin >> amount;    // read in the amount
    std::vector<std::string> strings;
    for (int i = 0; i < amount; i++) {
        std::string s;
        std::cin >> s;          // read in the nth string
        strings.push_back(s);   // add it to the vector
    }

    for (std::string s : strings) {
        std::cout << "string: " << s << std::endl;
    }
}

And pass input such as 3 H He Li.

Related