我有一个文件,格式为:
类(class) - 成绩计数 - 成绩
Programming 10 3 4 5 4 3 2 4 5 2 3
Mathematics 8 3 3 4 5 3 2 2 3
Physics 6 3 4 5 3 4 5
Design 6 5 4 5 3 2 4
Logistics 8 3 4 5 3 1 1 2 4
例如:类(class) - 编程、成绩计数 - 10 和成绩 - 3 4 5 4 3 2 4 5 2 3
我已经有了
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 70
int main(void)
{
char subject[SIZE];
int gradeCount;
int grades[SIZE];
FILE *fp = fopen("C:\\Project\\project.txt", "r"); //opening already created file
if (fp == NULL) {
perror("Error opening file");
return(-1);
}
for (int i = 0; i < SIZE; i++) {
fscanf(fp, "%s %d", &subject[i], &gradeCount);
printf("%s \n", &subject[i]);
//printf("%d \n", gradeCount);
for (int k = 0; k < gradeCount; k++)
{
fscanf(fp, "%d", &grades[k]);
// printf("%d \n" , grades[k]);
}
if (i == SIZE) {
break;
}
}
fclose(fp);
return 0;
}
我需要毫无问题地打印出“类(class)”、“成绩计数”和“成绩”,稍后我需要进行搜索,所以我需要将它们彼此分开,但事实并非如此,现在,我将向您展示所有情况下的输出,即我首先输出“科目/类(class)”,然后输出“成绩计数”,最后输出“成绩”。
对于类(class):
Programming
Mathematics
Physics
Design
Logistics
ogistics
gistics
istics
stics
tics
ics
cs
s
@
@@
@
@
对于成绩计数:
10
8
6
6
8
8
8
8
8
8
8
8
8
8
8
8
8
8
8
8
对于成绩:
3
4
5
4
3
2
4
5
2
3
3
3
4
5
3
2
2
3
3
4
5
3
4
5
5
4
5
3
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
3
4
5
3
1
1
2
4
在所有情况下,附加的东西都会添加到应该打印出来的原始内容中,我不知道它来自哪里,我考虑过指针,但对它们了解不多。有什么建议么?
只需正常打印所有内容即可稍后正常搜索所有内容(类(class)、成绩计数和成绩)。
最佳答案
如果无法读取任何内容,您需要提前退出循环。您可以通过检查 fscanf
的返回值来做到这一点。如果第一个调用不返回 2,您就知道它没有读入 2 个值,并且可以break
跳出循环。
您还错误地调用了 fscanf
和 printf
来处理字符串。您正在移动读取/打印的起点,这是不必要的,并且会减少您可用的最大空间。
更新后的代码看起来像这样
for (int i = 0; i < SIZE; i++) {
if(fscanf(fp, "%s %d", subject, &gradeCount) != 2) {
break;
}
printf("%s ", subject);
//printf("%d \n", gradeCount);
for (int k = 0; k < gradeCount; k++)
{
fscanf(fp, "%d", &grades[k]);
// printf("%d" , grades[k]);
}
}
关于C - 输出比文件中的大(大小问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53412774/