【问题标题】:Read and modify txt file (line by line)读取和修改txt文件(逐行)
【发布时间】:2017-11-19 22:32:32
【问题描述】:

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

  • “#”个学生:

  • 平均年龄:

  • 平均 gpa:

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

【问题讨论】:

  • 在您不能放入 C.I.e. 的代码周围至少提供 minimal reproducible example main()、scan & Co、printf。并采取tour,特别寻找How to Ask
  • 我认为不需要排序。但是如果排序只是为了好玩,结果应该覆盖输入文件吗?标题似乎是“逐行”,它与排序等整个文件操作不匹配。而且,只要您之后不覆盖整个文件,也不会发生“修改”。

标签: c data-structures struct structure


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    相关资源
    最近更新 更多