我正在撰寫一個代碼來輸入主題的資訊,我將 void 函式和陣列作為一個物件。但不確定我什么時候想回圈它,它直到最后才出現。看看代碼。
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=1; year<=4; year ) {
for (sem=1; sem<=2; sem ) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 1; i <= totalSubjectSem; i ) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
return 0;
}

這是錯誤。您可以看到編譯器僅在輸入主題名稱之前顯示,但省略了學時和成績。我應該怎么辦?
預期:它應該在 void 函式中直到 3(因為我輸入 3),然后重新開始“輸入你在第 1 sem 2 中學習的總科目”,但它也忽略了
uj5u.com熱心網友回復:
請注意,在 C 中,0 是第一個元素,n-1 是最后一個元素。通過回圈到 n,會導致緩沖區溢位,從而導致錯誤。
解決方案如下
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=0; year<4; year ) {
for (sem=0; sem<2; sem ) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 0; i < totalSubjectSem; i ) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
}
uj5u.com熱心網友回復:
計算 CGPA ob[totalSubjectSem];
它是 GCC 擴展,稱為Variable-length automatic arrays and not valid C (because totalSubjectSemis not const)。改用std::vector<calculateCGPA>。
for(int i = 1; i <= totalSubjectSem; i ) {
索引從 0 開始到array_length - 1. 在上一次迭代中,您讀取了陣列邊界并且程式崩潰了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537129.html
標籤:C
下一篇:BOOST_FUSION_ADAPT_STRUCT使用帶有std::vector<self_type>成員的遞回結構
