gpt4 book ai didi

c - 用C读取文件并将数据存储在数组中

转载 作者:行者123 更新时间:2023-11-30 15:45:40 24 4
gpt4 key购买 nike

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

最佳答案

第一: 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]); 之后。

关于c - 用C读取文件并将数据存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18924667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com