我是 stackoverflow 社区的新手,也是编码的新手,所以在我了解在这里发帖的技巧以及编码规则时提前道歉。我正在使用 C++,并且正在参加 CS161 初学者计算机科学课程。
我目前正在做一项作业,该作业要求我从存储在计算机上的数据文件中读取数据并对数据进行排序以进行一些计算,在此作业中,根据性别和学校类型查找平均考试成绩。一切都编译并且程序运行但是有一些问题。
第一个问题是我的回声。
// echo the data file
while (inData)
{
inData >> name >> sex >> school >> score;
cout << name << sex << school << score << endl;
该程序确实回显了数据,但由于某种原因,它最终回显了列表中的姓氏两次。此外,(我不知道这是否重要)当它回显时,它不会跳过姓名、性别、学校和分数之间的空格。
第二个问题是它没有执行计算,我认为这是因为我错过了某种与“计数”相关的指令,但我无法做到。
这是我的代码,让我知道你的想法:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
//Declare variables to manipulate data
char sex;
string name;
string school;
string fileSource;
string CC;
string UN;
int maleScore = 0;
int femScore = 0;
int unScore = 0;
int ccScore = 0;
double maleAvg;
double femAvg;
double unAvg;
double ccAvg;
double sumAvg = 0;
int femCount = 0;
int maleCount = 0;
int ccCount = 0;
int unCount = 0;
int score;
int sum;
//Declare stream variables
ifstream inData;
ofstream outData;
inData >> name >> sex >> school >> score;
// Promt user for file location
cout << "Please input file location: ";
cin >> fileSource;
// open output file and run program exit failsafe command
inData.open(fileSource);
if (!inData)
{
cout << "Cannot open input file. "
<< "Program will now terminate." << endl;
return 1;
}
outData << fixed << showpoint << setprecision(2);
// echo the data file
while (inData)
{
inData >> name >> sex >> school >> score;
cout << name << sex << school << score << endl;
// while reading incoming data from file, execute the conditions
// Male and female calculations
if(sex=='M')
{
maleScore = maleScore +=score;
++maleCount;
}
else if(sex =='F')
{
femScore = femScore +=score;
++femCount;
}
// Community college and University calculations
if(school == CC)
{
ccScore = ccScore +=score;
++ccCount;
}
else if(school == UN)
{
unScore = unScore +=score;
++unCount;
}
maleAvg = maleScore/maleCount;
}
// Male average output
cout << maleAvg;
femAvg = femScore/femCount;
// Female average output
cout << femAvg;
ccAvg = ccScore/ccCount;
// Community College average output
cout << ccAvg;
unAvg = unScore/unCount;
// University average output
cout << unAvg;
sum = maleScore + femScore + ccScore + unScore;
sumAvg = sum/12;
cout << sumAvg;
return 0;
}
此外,我的编译器继续运行程序并且不会停止。我拍了一张编译器窗口的照片,但不知道如何发布。