在数组中获取多个输入

时间:2014-08-05 23:22:01

标签: c++ arrays names

对于此代码,我有用户输入但是他/她想要的许多学生然后要求他们输入他们的名字和测试分数。

#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;
}

我知道这段代码有很多错误,但我的主要目标是如何将名称和分数变成并行数组。谢谢!

3 个答案:

答案 0 :(得分:1)

你会在while循环中抛出所有内容,然后在用户想要退出时将其中断。但是,您如何知道用户何时想要退出?对于像抓取名字和年龄这样的东西,可能是当用户为名称输入“-1”时,它看起来像:

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);
}

答案 1 :(得分:0)

创建一个变量来存储来自用户的答案。循环工作。在每个循环中询问用户的输入作为答案。把条件检查用户的选择。 例如:

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);

此程序一直持续到用户回答1(并且其他值为中断,可能为0)。

希望这就是你要找的东西。

答案 2 :(得分:0)

您的此功能:

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

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

可以是:

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