You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于给定模板的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:

  1. Handling Names with Spaces

    • Used getline to read full lines, then istringstream to 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").
  2. Fixed Loop Logic

    • Replaced while (inFile) with while (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.
  3. Correct Grade Display

    • In the final loop, we calculate pct for 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.9 since previous conditions already cover higher scores).
  4. Error Handling

    • Added exit(EXIT_FAILURE) if the file fails to open, so the program doesn't attempt to process non-existent data.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:33:10