我的代码在C中读取文件。它显示文件,平均分数,最高分数以及获得最高分的所有学生的姓名。考试分数(0-100格式到1位小数并使用字段宽度的列)存储在一个数组中,名称(名称和姓氏限制为15个字符)存储在一个二维字符数组中,即与得分数组平行。我的问题是:
1)代码没有正确读取(打印)文件(我认为与fscanf和数组有关)。
2)我的两个功能不打印结果。
任何建议都表示赞赏,谢谢。
#include "tools.h"
#define MAX 30 // Maximum number of students
int computeMax(double stSco[], int numSt); // Gets the average and highest
// score
void outputBest(double num[], char nameHg[][15], int hgPl, int totStu);
int main()
{
double score[MAX];
char name[MAX][15];
char fileName[80];
int k, count = 0, hgCt;
stream dataFile;
banner();
printf("Type the name of file you want to read\n");
scanf("%79[^/n]", fileName);
dataFile = fopen(fileName, "r");
if (dataFile == NULL)
{
fatal("Cannot open %s for input", fileName);
}
while (!feof(dataFile))
{
fscanf(dataFile, "(%lg,%s)", &score[k], &name[k]);
printf("%6.1f %s\n", score[k], name[k]);
count++; // It counts how many students there are
}
hgCt = computeMax(score, count); // Stores the value sent by the
// function
outputBest(score, name, hgCt, count);
fclose(dataFile);
bye();
return 0;
}
int computeMax(double stSco[], int numSt)
{
int k, maxScore = 0, sum = 0;
double maximum = 0, average = 0;
for (k = 0; k < numSt; k++)
{
sum += stSco[k]; // It sums all scores
if (stSco[k] > maximum)
{
maximum = stSco[k];
maxScore = k; // Stores the index of the maximum score
}
}
average = sum / numSt;
printf("The average score is %d\n", average);
printf("The maximum score is %d\n", maximum);
return maxScore;
}
void outputBest(double num[], char nameHg[][15], int hgPl, int totStu)
{
int k;
for (k = 0; k < totStu; k++)
{
if (num[k] = hgPl)
{ // It finds who has the highest score
printf("%s got the highest score\n", nameHg[k]);
}
}
}
答案 0 :(得分:1)
首先:scanf("%79[^/n]",fileName);
应为scanf("%79[^\n]",fileName);
,最好使用fgets()
。
第二个拼写错误:在==
条件下=
拼错了if()
if(num[k]=hgPl){ //It finds who has the highest score
// ^ = wrong
应该是:
if(num[k] == hgPl){ //It finds who has the highest score
修改:
while循环错误..
fscanf(dataFile, "(%lg,%s)", &score[k], &name[k]);
// ^ ^ ^ remove ^
应该是:
fscanf(dataFile, "%lg%14s", &score[k], name[k]);
并在while循环中增加k
。在printf("%6.1f %s\n", score[k], name[k]);
之后。