2014-10-28 107 views
0

我對如何將字符串存儲在數組中存在一些混淆。該計劃的目標是從控制檯接收一些學生和一些測驗,然後計算每個學生測驗分數的平均值,這很容易。雖然我在嘗試接收學生姓名時遇到了一些問題(根據用戶給我的學生人數,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); 
    } 

^主程序。問題發生在外循環中。我不得不接受循環內的名字,因爲我不知道在運行時需要輸入多少個名字。在循環結束後,我還必須在程序後面顯示名稱,所以我不能在循環內部做一個簡單的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 

回答

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; 
} 
相關問題