从控制台读取字符串并将其存储在数组中

时间:2014-10-28 21:42:50

标签: c++ arrays string input

我对如何在数组中存储字符串感到困惑。该计划的目标是从控制台接收一些学生和一些测验,然后计算每个学生的所述测验成绩的平均值,这很容易。虽然我在尝试接收学生姓名时遇到了一些问题(根据用户给我的学生人数,1-10个字符串)。我可以考虑采用这种数据的唯一方法是使用for循环,因为我需要读入的名称数量由用户输入决定。我想将名称存储在数组中,但我不确定如何执行此操作。任何帮助,将不胜感激。代码如下。

int main()
{
    int students = 0;
    getStudents(students);

    int quizzes = 0;
    getQuizzes(quizzes);

    char* studentArray = new char[students];
    int* quizArray = new int[quizzes];
    double* studentAverage = new double[students];

    char student_name[20];
    for(int i = 0; i < students; i++)
    {
        cout << "Enter the students name: ";
        cin.get (student_name, 20);
        cin.ignore(' ','\n');
        studentArray[i]=student_name;
        for(int j = 0; j < quizzes; j++)
        {
            cout << "Enter quiz " << j+1 << ":";
            cin >> quizArray[j];
        }
        studentAverage[i] = calculateAvergage(quizArray,quizzes);
    }

^主程序。问题发生在外部for循环中。我被迫接受循环中的名字,因为我不知道在运行时要接受多少个名字。我还必须在循环结束后在程序中稍后显示名称,这样我才能做一个简单的cout&lt;&lt;在循环中。

for(int i = 0; i < students; i++)
{
    cout << studentArray[i] << setw(10) << studentAverage[i] << endl << endl;
}

^在程序结束时显示数据的循环。

我还会添加输出应该是什么样子以便进行一些澄清

How many students?  2
How many quizzes?  3

Enter the students name:  John Smith
Enter Quiz 1: 90
Enter Quiz 2: 80
Enter Quiz 3: 75
Enter the students name: John Jones
Enter Quiz 1: 100
Enter Quiz 2: 90
Enter Quiz 3: 80

Student              Quiz Average
---------------------------------
John Smith               81.67
John Jones               90.00

1 个答案:

答案 0 :(得分:0)

You can modify the below code to suit your needs. It takes a string and integer.
#include <iostream>
#include<vector>
#include <string>
int main()
{
std::string name;
int num;
std::vector<std::string> stringList;
std::vector<int> intList;
while( std::cin >> name >> num )
{
    //enter stop and 0 to stop
    if (!name.compare("stop") && num == 0) break;
    stringList.push_back(name);
    intList.push_back(num);

}
std::copy(stringList.begin(), stringList.end(), std::ostream_iterator<std::string> (std::cout,","));
std::cout << std::endl;
std::copy(intList.begin(), intList.end(), std::ostream_iterator<int>(std::cout ,",") );
std::cout << std::endl;
return 0;
}