【发布时间】:2018-11-21 13:08:48
【问题描述】:
我有一个文件,格式为:
课程 - 成绩计数 - 成绩
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
例如:课程 - 编程、年级数 - 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;
}
我需要打印出“Course”、“Grade Count”和“Grades”没有任何问题,稍后我需要进行搜索,所以我需要将它们彼此分开,但事实并非如此,现在我将向您展示所有案例的输出,当我首先输出“主题/课程”,然后是“成绩计数”,最后是“成绩”时。
对于课程:
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
在所有情况下,在应该打印出来的原始内容中添加了额外的东西,我不知道它来自哪里,我考虑过指针,但对它们了解不多。有什么建议么?
只需正常打印所有内容,以便以后正常搜索所有内容(课程、成绩计数和成绩)。
【问题讨论】:
-
首先在代码中添加错误检查;尤其是
fscanf()。 -
怀疑你错误地声明了
subject- 看起来你期望它是一个字符串数组,但你只是把它作为一个字符串。 -
if (i == SIZE)在你的循环中永远不会发生,因为你只在i < SIZE时循环。如果没有更多输入,您必须考虑一种更好的方法来退出循环。 -
@ChrisTurner 字符数组,它应该是一个字符串,这就是想法。
-
字符串是
chars 的数组。字符串数组是chars 的数组。