0

我下面的代码读取 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]);
        }
    }
}
4

1 回答 1

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]);

k并在while循环中递增。之后printf("%6.1f %s\n", score[k], name[k]);

于 2013-09-20T19:48:10.810 回答