gpt4 book ai didi

c - C语言如何从文件中读取数据?

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:02 25 4
gpt4 key购买 nike

我有一个包含信息的文件

0001:Jack:Jeremy:6:38.0
0002:Mat:Steve:1:44.5
0003:Jessy:Rans:10:50.0
0004:Van Red:Jimmy:3:25.75
0005:Peter:John:8:42.25
0006:Mat:Jeff:3:62.0

我想从这个文件中获取数据,这样这个字符串的每个部分都会有每个值。例如,double num 将是 3; char firstn[20] 将为“Jack”,char lastn[20] 将为“Jeremy”,int t 将为 6,并且double hour 将为 38.0,依此类推。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
FILE *read, *write;
int i, group;
double hours, num;
char lastn[20],
firstn[20];

read = fopen("people.txt", "r");
if (read == NULL) {
printf("Error, Can not open the file\n");
exit(0);
}
write = fopen("people.dat", "w");
for (i=0; i<6; i++) {
fscanf(read, "%lf:%s:%s:%d:%lf", &num, lastn, firstn, &group, &hours);
fprintf(write, "Number: %lf Fname: %s Lastn: %s Group: %d Hours: %.1lf\n", num, lastn, firstn, group, hours);
}
fclose(read);
fclose(write);

return 0;
}

当我尝试这样做时,我的字符串 lastn 获取了所有信息,直到行尾。

我如何指定字符串 firstn 将只接受字符直到 : 然后字符串 lastn 将只接受 Jeremy,组将接受只有 6 个,等等?

最佳答案

您可以修改您的fscanf() 格式字符串。

if (fscanf(read, "%lf:%19[^:]:%19[^:]:%d:%lf", &num, lastn, firstn, &group, &hours) != 5)
...the read failed...

符号 %19[^:] 表示“读取最多 19 个非冒号字符”到字符串中,后跟一个空值。请注意,变量 lastnfirstnchar[20]。请注意,已检查转换;如果您得到 5 以外的答案,则说明出了问题。您可能会考虑在 fscanf() 调用之后扫描行的其余部分直到换行:

int c;
while ((c = getc(read)) != EOF && c != '\n')
;

您还应该检查您是否成功打开了输出文件。

关于c - C语言如何从文件中读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9952420/

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