gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:28:05 26 4
gpt4 key购买 nike

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

  • “#”名学生:

  • 平均年龄:

  • 平均绩点:

问题是我脑子里有这个想法,但我似乎无法将其付诸代码。有人可以帮我解决这个问题吗?

最佳答案

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

针对 OP 问题的此类步骤类似于:

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

关于c - 读取并修改txt文件(逐行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com