gpt4 book ai didi

c++ - 数组 C++ 的 Ofstream 文本编写问题

转载 作者:行者123 更新时间:2023-11-28 07:13:05 24 4
gpt4 key购买 nike

好吧,我已经两次遇到问题的臭名昭著的代码项目已基本重新格式化。现在,它看起来像这样:

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

using namespace std;


struct Course
{
string name;
double grade;
int block;
};

Course enter_course()
{
Course foo;

cout << "What is the name of the course you wish to enter?\n";
cin >> foo.name;
cout << "What block is " << foo.name << " ?\n";
cin >> foo.block;
cout << "What is your current grade as a percent?";
cin >> foo.grade;

return foo;
}

void display_courses(Course courseList[10], int courseCount)
{
for (int i=0; i<courseCount; i++){
cout << i+1 << "\t" << courseList[i].name
<< "\t\tBlock: " << courseList[i].block
<< "\tGrade: " << courseList[i].grade << "%" << endl;
}
}

double get_gpa(Course courseList[10], int courseCount)
{
double gradePoints;
double total = 0.0;
for (int i=0; i<courseCount; i++){
if (courseList[i].grade < 100){
gradePoints = 4;
}
if (courseList[i].grade < 90){
gradePoints = 3;
}
if (courseList[i].grade < 80){
gradePoints = 2;
}
if (courseList[i].grade < 70){
gradePoints = 1;
}
if (courseList[i].grade < 90){
gradePoints = 0;
}
total += gradePoints;
}

return total*1.0/courseCount;

}

void fileOutput()
{
ofstream outputFile;
outputFile.open("userGrades.txt");
outputFile << myCourses[10] << endl;
outputFile.close();
cout << "Grades saved to file!" << endl;
}

void display_options()
{
cout << "1. Exit\n";
cout << "2. Enter a Course\n";
cout << "3. Display Courses\n";
cout << "4. Display GPA\n";
cout << "5. Request a text file output\n";

cout << "\n\n";
}

int main()
{
bool exit=0;
int option;
int courseCount=0;
Course myCourses[10]; //nobody should ever take more than 10 courses!

while (exit == 0)
{
cout << "GradeBook 2.0\n";
display_options();
cout << "Enter a command.\n";
cin >> option;

switch (option)
{
case 1:
exit = 1;
break;
case 2:
myCourses[courseCount] = enter_course();
courseCount++;
break;
case 3:
display_courses(myCourses, courseCount);
break;
case 4:
cout << get_gpa(myCourses, courseCount) << endl;
break;
case 5:
fileOutput();
break;
}
}

return 0;
}

但是,在 fileOutput() 函数中,同一行代码我遇到了这些错误:

错误 C2065:“我的类(class)”:未声明的标识符IntelliSense:标识符“myCourses”未定义

我唯一能理解的是我需要在别处声明 myCourses,但我不知道如何声明。

有人认为他们可以解决这个问题吗?如果是这样,请编译代码并查看。此外,get_gpa 函数似乎无法正常工作,如果您也可以查看一下。

最佳答案

您的 Course 类没有 ostream 运算符,因此您不能在这一行中调用该运算符:

   outputFile << myCourses[10] << endl;

您可以尝试删除该行并放入:

display_courses(myCourses,courseCount)

但遗憾的是打印到 cout。因此,您确实需要重写 display_courses 以获取 ostream& 参数并输出到它,而不是 cout

关于c++ - 数组 C++ 的 Ofstream 文本编写问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20673758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com