Kara
Kara

Reputation: 785

Store multiple inputs into an array

Let's say the user inputs

Sarah Freshman Computer Science Major
John Sophomore Math Major

I was wondering how am I able to store these multiple inputs into a list?

Name = [Sarah, John]
Year = [Freshman, Sophomore]
Major = [Computer Science Major, Math Major]

I am able to store the first two (Sarah/Freshman & John/Sophomore) into a list, but the latter part is hard because the major is separated into spaces.

--Edit: Example Code--

I am new to C++ and am trying to create a program that asks the user personal questions.

std::vector<std::string> name, year, major;
std::cout << "Hello, what is your Name Year Major? "; //asks user first
std::cin << name;
std::cin << age;
std::cin << major;

int n;
std::cout << "How many students will you input? ";   //enter other students info
std::cin << n;

for (int a=0;a<n;a++){
    std::cout << "Please enter Name Age Major for student #" << a << ": ";
    std::string a, b, c;
    std::cin >> a;
    std::cin >> b;
    std::cin >> c; //this part throws me off
    name.push_back(a);
    age.push_back(b);
    major.push_back(c);

}

Upvotes: 0

Views: 2244

Answers (3)

herohuyongtao
herohuyongtao

Reputation: 50657

Use the reading-and-then-parsing strategy:

vector<string> name;
vector<string> year;
vector<string> major;

string line;
while(getline(cin, line)) // 1. reading...
{
    if (line == "0") // enter 0 to finish input
        break;

    // 2. parsing...
    int first = line.find(" "); // position of the first space
    int second = line.find(" ", first+1); // position of the second space

    name.push_back(line.substr(0, first));
    year.push_back(line.substr(first+1, second-first-1));
    major.push_back(line.substr(second+1));
}

Upvotes: 0

IllusiveBrian
IllusiveBrian

Reputation: 3204

Since others have mentioned how to do this by changing your input, a way you could do it without changing your input is to check if the word you are reading is the first word of a major (IE "Computer" "Math" etc) and use getline to the end of the line if you see that it is. If your input is going to be exactly like this, checking if a word was one of the class years would probably work even better, since you don't need to do any appending and the list of words to check is much smaller.

Alternatively, if you know that the form is always "First Name", "Class Year", "Major" you can simply start a getline after the second word read.

Upvotes: 1

Ranveer
Ranveer

Reputation: 6863

Suggestion 1:

Use a getline() and insert a special character after every word and tell your program to mark the input as next input only upon encountering the special character. It's even easier in your case -- whenever the program encounters the word "Major", it goes to the next input.

Suggestion 2:

Input as Computer_Science_Major and later change _ to space in you program.

Upvotes: 0

Related Questions