为什么这个C++程序不能得到文本文件中的输出?

问题描述 投票:0回答:2
#include<iostream> 
#include<fstream> 
#include<iomanip> 
#include<string>

using namespace std;

char calculate_grade(double avg);

char calculate_grade(double avg) {
    if (avg >= 80) { return 'A'; }
    else if (avg >= 70) { return 'B'; }
    else if (avg >= 60) { return 'C'; }
    else if (avg >= 50) { return 'D'; }
    else { return 'F'; }
}

int main() {
    ifstream infile("StudentData.txt");
    ofstream outfile("ResultData.out");

    string name;
    double math, eng, sci, avg;

    outfile << left << setw(10) << "Name"
        << setw(10) << "MATH"
        << setw(10) << "ENG"
        << setw(10) << "SCI"
        << setw(10) << "AVG"
        << setw(10) << "GRADE" << endl;

    while (infile >> name >> math >> eng >> sci) {
        double avg = (math + eng + sci) / 3.0;

        char grade = calculate_grade(avg);

        outfile << setw(10) << name << " "
            << setw(10) << math << " "
            << setw(10) << eng << " "
            << setw(10) << sci << " "
            << setw(10) << avg << " "
            << setw(10) << grade << " " << endl;

    }

    infile.close();
    outfile.close();

    return 0;
}

我想用一个文本文件的内容,让C++帮我算出学生的平均分和成绩,然后输出到文本文件里,可是我搞不定。我不知道怎么做或哪里错了

我是 C++ 的新手,所以如果它确实有一个简单的答案,我很抱歉。但无论如何,我已经调试了几个小时,我也上网看了几次

c++ ifstream ofstream
2个回答
0
投票

文件内容很重要。而且您甚至没有检查文件是否已打开。除非您编写代码来处理它们,否则不会有错误。

输入也有问题。名称是一个字符串。

infile >> name
会吃掉整个记录。


-1
投票

假设您完全复制并粘贴了代码,则不允许在一行中有多个

include
语句,这会阻止编译。相反,将每个
include
放在不同的行上:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

这应该可以修复您遇到的任何编译错误。

© www.soinside.com 2019 - 2024. All rights reserved.