簡體   English   中英

從控制台讀取字符串並將其存儲在數組中

[英]Reading strings from the console and storing them in an array

我對如何在數組中存儲字符串有些困惑。 該程序的目的是從控制台中招募許多學生和許多測驗,然后計算每個學生的所述測驗平均成績,這很容易。 雖然在嘗試輸入學生姓名時會遇到一些問題(根據用戶給我的學生人數,使用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 <<。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM