基于给定模板的C++学生成绩处理程序开发求助:结构体数组存储与成绩计算实现指导
Fixing Your C++ Student Grade Program
Let's work through fixing your code while respecting the constraints you mentioned (keeping the letterGrade, students[24], and newStudent variables intact). I'll address each of the commented sections and fix the hidden bugs that are causing your program to fail.
First, add the missing header we need for parsing lines with spaces:
#include <sstream> // For handling name strings with spaces
Step-by-Step Fixed Code with Explanations
#include <iostream> #include <cstdlib> #include <string> #include <fstream> #include <sstream> // Added for line parsing using namespace std; /* structure */ struct Student { string name; double midTerm; double finalExam; double lab1; double lab2; double lab3; double lab4; }; /* function prototype */ double calculateGrade(Student s); /* main function */ int main(void) { Student newStudent; Student students[24]; ifstream inFile; int numStudent = 0; char letterGrade = ' '; string line; // Added to hold full lines from the file inFile.open("students.txt"); if (!inFile) { cerr << "Unable to open file.\n"; exit(EXIT_FAILURE); // Exit immediately if file can't open } // Read each line until end of file (fixes extra empty record bug) while (getline(inFile, line)) { istringstream lineStream(line); // Convert line to a stream for parsing string namePart; newStudent.name = ""; // Read name parts until we hit a number/decimal (handles spaces in names) while (lineStream.peek() != EOF && !isdigit(lineStream.peek()) && lineStream.peek() != '.') { lineStream >> namePart; if (!newStudent.name.empty()) newStudent.name += " "; newStudent.name += namePart; } // Read all numeric scores from the line lineStream >> newStudent.midTerm >> newStudent.finalExam >> newStudent.lab1 >> newStudent.lab2 >> newStudent.lab3 >> newStudent.lab4; // Calculate final score for current student double pct = calculateGrade(newStudent); // Store student in array and increment count students[numStudent] = newStudent; numStudent++; // No need for ignore() — getline already consumed the newline character } // Fix grade display: calculate each student's score individually for (int i = 0; i < numStudent; i++) { double pct = calculateGrade(students[i]); // Recalculate per student (not reuse old value) if (pct >= 90.0) letterGrade = 'A'; else if (pct >= 80.0) // Simplified conditions (no redundant upper bounds) letterGrade = 'B'; else if (pct >= 70.0) letterGrade = 'C'; else if (pct >= 60.0) letterGrade = 'D'; else letterGrade = 'F'; cout << students[i].name << "'s final grade is " << pct << "% (grade: " << letterGrade << ")" << endl; } exit(EXIT_SUCCESS); } double calculateGrade(Student s) { double exams, labs; exams = 0.25 * s.midTerm + 0.25 * s.finalExam; labs = 0.125 * (s.lab1 + s.lab2 + s.lab3 + s.lab4); return exams + labs; }
Key Fixes & Notes:
Handling Names with Spaces
- Used
getlineto read full lines, thenistringstreamto split lines into parts. This lets us collect all non-numeric segments as the student's name (e.g., "Susan F. Smith" is read correctly instead of just "Susan").
- Used
Fixed Loop Logic
- Replaced
while (inFile)withwhile (getline(inFile, line))to avoid reading an extra empty record at the end of the file. - Moved
numStudent++to after storing the student in the array, so the count stays in sync with valid records.
- Replaced
Correct Grade Display
- In the final loop, we calculate
pctfor each student individually instead of reusing the last value from the read loop. This ensures every student gets their correct grade. - Simplified letter grade conditions (no need for
<=89.9since previous conditions already cover higher scores).
- In the final loop, we calculate
Error Handling
- Added
exit(EXIT_FAILURE)if the file fails to open, so the program doesn't attempt to process non-existent data.
- Added
Your calculateGrade function is already correct—it properly weights midterms (25%), finals (25%), and lab averages (50%) since 0.125 * 4 labs = 0.5 total weight.
内容的提问来源于stack exchange,提问作者jr.çhåvez__07
相关产品推荐
相关产品推荐

