更新时间:2023-11-21 09:34:04
首先: scanf函数(%79 [^ / N],文件名);
应 scanf函数(%79 [^ \\ n],文件名);
,***使用与fgets()
。
二错字错:拼错 ==
按 =
在如果()
状态
如果(NUM [K] = hgPl){//它发现谁得分最高
// ^ =错误
应该是:
如果(NUM [K] == hgPl){//它发现谁得分最高
编辑:
错误while循环。
的fscanf(数据文件,(LG%,%S),&安培;比分[K],和放大器;名称[K]);
// ^ ^ ^ ^删除
应该是:
的fscanf(数据文件,LG%14S%,&安培;比分[K],名称[K]);
和增量 K
在while循环。在的printf(%6.1F%S \\ n,得分[K],名称[K]);
。
My code below reads a file in C.It displays the file, the average score, maximum score,and the names of all the students who earned the maximum score. The exam scores(0-100 format to 1 decimal place and use a field width of columns) are stored in an array and the names(name and last name limited to 15 characters) are stored in a 2-dimensional array of characters that is parallel to the scores array. My problems are:
1) The code doesn't read(print) the file properly (I think is related to fscanf and the arrays).
2) My two functions don't print the results.
Any suggestion is appreciated, thanks.
#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]);
}
}
}
First: scanf("%79[^/n]",fileName);
should be scanf("%79[^\n]",fileName);
, better to use fgets()
.
Second typo mistake: misspelled ==
by =
in if()
condition
if(num[k]=hgPl){ //It finds who has the highest score
// ^ = wrong
should be:
if(num[k] == hgPl){ //It finds who has the highest score
Edit:
Error in while loop..
fscanf(dataFile, "(%lg,%s)", &score[k], &name[k]);
// ^ ^ ^ remove ^
should be:
fscanf(dataFile, "%lg%14s", &score[k], name[k]);
and increment k
in while loop. after printf("%6.1f %s\n", score[k], name[k]);
.