c - 读取和修改 txt 文件(逐行)



所以在我过去的一个课程中有一个轻量级项目,用户可以在其中读取文本文件(我们称之为"studentstuff.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"将根据结构进行读取和排序,然后在一些小数学和函数之后吐出:

  • "#"学生人数:

  • 平均年龄:

  • 平均年薪:

问题是我脑子里有这个想法,但我似乎无法将其放入代码中。谁能帮我解决这个问题?

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

OPs 问题的一组步骤类似于:

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 语句的分离。 它在这里没有任何区别,但在使用调试器(需要结构标记名称才能正确显示结构中的所有字段(以及处理大型项目以帮助避免混淆时会有任何区别。

最新更新