Kara
Kara

Reputation: 785

How to get a certain element from multiple inputs C++

I want to get a certain element based on what the user inputs in different lines. I am new to C++ programming so I am unsure of what route to take.

std::string siblings;
std::string names;

std::cout << "Please enter how many siblings you have: ";
std::cin >> siblings;

for (int x=0;x<siblings;x++){
    std::cout << "Please enter your sibling(s) name: ";
    std::cin >> names;
}

So if the user entered '3' siblings and typed in Mark, John, Susan, how do i get the name of the 2nd sibling - "John"? Or perhaps the first name entered, or last?

**Also, I wanted the question to just ask once and wait for the user to put in X amount of siblings based on what they put on different lines, then continue onto the program, but the question is repeatedly asking.

Upvotes: 0

Views: 106

Answers (1)

Shoe
Shoe

Reputation: 76240

First of all you should define siblings as an int rather than an std::string, otherwise your use of operator< in the for loop, won't work. Second, you should use an std::vector and push the names inside the for loop. Here's the complete working code:

int siblings = 0;
std::vector<std::string> names;

std::cout << "Please enter how many siblings you have: ";
std::cin >> siblings;

for (int x = 0; x < siblings; x++) {
    std::string current;
    std::cout << "Please enter the name for sibling #" << (x + 1) << ':';
    std::cin >> current;
    names.emplace_back(current);
}

The above code will ask the number of siblings and then will ask for each sibling the name and push it into names.

If you really want to adventure yourself into the magic world of string formatting with C and C++, take a look at this other question.

Upvotes: 1

Related Questions