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

Reading strings from the console and storing them in an array

本文关键字:存储 数组 串并 控制台 读取 字符 字符串      更新时间:2023-10-16

我对如何在数组中存储字符串感到困惑。该程序的目的是从控制台接收一些学生和一些测验,然后计算每个学生所述测验成绩的平均值,这很容易。尽管我在尝试输入学生姓名时遇到了一些问题(根据用户给我的学生人数,有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;循环内部。

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