2017-06-17 165 views
-4

因此就出现了我过去的一个类有鉴于此项目中,用户会阅读的文本文件(让称它为“studentstuff.txt”,见下文)读取和修改txt文件(逐行)

*studentstuff.txt* 

1 
Bob Smith 
24 
3.5 
2 
Jill Williams 
23 
3.6 
3 
Tom Jones 
32 
2.4 
4 
Julie Jackson 
21 
3.1 
5 
Al Brown 
23 
3.35 
6 
Juan Garcia 
22 
3.4 
-7 
Melissa Davis 
20 
3.2 
8 
Jack Black 
44 
1.1 

并输出结果:1)学生数量2)平均年龄3)平均gpa。在这个作业,我们有一个结构:

typedef struct{ 
    int id; 
    char name[255]; 
    int age; 
    float gpa; 
}student; 

根据该计划,“studentstuff.txt”将根据结构再经过一些小的数学和功能吐出阅读并排序

  • 学生的 '#':

  • 平均年龄:

  • 平均GPA:

问题是我的想法在我脑海中,但我似乎不能将它放入代码。任何人都可以帮我解决这个问题吗?

+5

至少在你不能放入C的代码周围提供[mcve]。 main(),scan&Co,printf。然后参加[游览],特别是[问]。 – Yunnosch

+0

我看不到需要排序。但是如果排序只是为了好玩,结果应该覆盖输入文件吗?标题似乎说“一行一行”,这不符合排序等整个文件操作。而且,只要你以后不覆盖整个文件,也不会发生“修改”。 – Yunnosch

回答

0

与任何编程问题一样,第一个动作(决定输入和输出之后)是将问题分解为简单的离散步骤。

这样的一组的用于有机磷农药问题的步骤将类似于:

open the input file 
if any errors: 
    output user message to stderr 
    exit program, indicating error occurred 
else 
    begin: loop: 
     input the info for one student 
     if any errors, except EOF: 
      output user message to stderr 
      cleanup by closing the input file 
      exit program, indicating an error occurred 
     else 
      update number of students 
      update total age 
      update total gpa 
     endif 
     goto top of loop 
    end loop: 
endif 

calculate the average age 
calculate the average gpa 

display number of students 
display average student age 
display average student gpa 

cleanup by closing the input file 
return to caller, indicating success 

由于计算将产生的级分,以避免出现问题,建议的结构被定义为:

struct studentStruct 
{ 
    float id; 
    char name[255]; 
    float age; 
    float gpa; 
}; 

typedef struct studentStruct student; 

注意结构定义与typedef语句的分离。在这里没有任何区别,但是在使用调试器(需要struct标记名来正确显示结构中的所有字段)以及使用大型项目​​以避免混淆时才会有所作为。