私はstackoverflowコミュニティに不慣れで、コーディングも初めてなので、ここに投稿するコツとコーディングのルールを学ぶ間、事前にお詫び申し上げます。私は C++ を使用しており、CS161 の初級コンピューター サイエンス クラスに参加しています。
私は現在、コンピューターに保存されているデータ ファイルから読み取り、データを並べ替えて計算を行うように求める課題に取り組んでいます。この課題では、性別と学校の種類に基づいてテストの平均点を見つけます。すべてがコンパイルされ、プログラムが実行されますが、いくつかの問題があります。
最初の問題は私のエコーにあります。
// echo the data file
while (inData)
{
inData >> name >> sex >> school >> score;
cout << name << sex << school << score << endl;
プログラムはデータをエコーしますが、何らかの理由でリストの姓を 2 回エコーすることになります。また、(これが問題かどうかはわかりませんが)エコーするとき、名前、性別、学校、スコアの間のスペースをスキップしません。
2番目の問題は、計算が実行されていないことです。これは、何らかの「カウント」関連の命令が欠落しているためだと思いますが、できる限り困惑しています。
これが私のコードです。あなたの考えを教えてください:
#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;
}
また、私のコンパイラはプログラムを実行し続け、停止しません。コンパイラ ウィンドウの写真を撮りましたが、投稿する方法がわかりません。