Cathie Deane
Cathie Deane

Reputation: 31

Get multiple inputs in an array

For this code, I have the user input however many students' he/she wants then asks them to enter their names and test scores.

#include <iostream>
using namespace std;

int main ()
{
int count = 0, students, names, scores;

//Ask for number of students
cout << "How many students are there?" << endl;
cin >> students;

//Loop
for (count = 0; count < students; count++)
{
    cout << "What are their names?" << endl;
    cin >> names;

    cout << "What are their scores?" << endl;
    cin >> scores;
}

I know there are many errors with this code, but my main objective is how to get the names and the scores into a parallel array. Thank you!

Upvotes: 0

Views: 2860

Answers (3)

vijay sharma
vijay sharma

Reputation: 131

your this function:

for (count = 0; count < students; count++)
{
    cout << "What are their names?" << endl;
    cin >> names;

    cout << "What are their scores?" << endl;
    cin >> scores;
}

can be:

vector<std::string> name_list(students);
vector<int> marks_list(students);
for (count = 0; count < students; count++)
{
    cin >> name_list[count]>>marks_list[count];
}

Upvotes: 0

scohe001
scohe001

Reputation: 15446

You would throw everything in a while loop, and then break it when the user wants to quit. But how do you know when the user wants to quit? For something like grabbing names and ages, it could be when the user enters "-1" for the name, which would look like:

std::vector<std::string> names;
std::vector<int> ages;
while(true) {
    std::string name;
    int age;

    std::cin >> name;
    if(name == "-1") break;
    std::cin >> age;

    names.push_back(name);
    ages.push_back(age);
}

Upvotes: 1

Nabin
Nabin

Reputation: 11776

Create a variable to store answer from user. Work in a loop. Ask input from user as answer in every loop. Put the condition to check the choice of user. For example:

int x = 1;//to store answer of user
int age;
do{
cout<<"Enter the age";
cin>>age;
//similarly for name

cout<<"You want to do again (1/0)?";
cin>>x;//if user inputs 1 then continues doing thing else breaks
}while(x==1);

This program continues till the user answers 1(and breaks for other values, may be 0).

Hope this is what you are looking for.

Upvotes: 0

Related Questions