gpt4 book ai didi

c程序无法正确读取文件

转载 作者:行者123 更新时间:2023-11-30 16:45:23 25 4
gpt4 key购买 nike

这里是创建和写入文件的代码。

#include <stdio.h>

int main(void) {

FILE *cfPtr;

if((cfPtr = fopen("clients.txt","w")) == NULL) {


puts("File could not be opened.");

}

else {

puts("Enter the account, name, and balance.");
puts("Enter EOF to end input.");
printf("%s", "? ");

unsigned int account;
char name[30];
double balance;

scanf("%d %29s %lf", &account, name, &balance);
//fprintf(cfPtr, "%d %s %f\n", account, name, balance);

while(!feof(stdin) ) {

fprintf(cfPtr, "%d %s %.2f\n", account, name, balance);
printf("%s", "? ");
scanf("%d%29s%lf", &account, name, &balance);

}

fclose(cfPtr);

}

return 0;

}

这里是读取文件并打印txt文件内容的代码。

#include <stdio.h>

int main(void) {

FILE *cfPtr;

if((cfPtr = fopen("clients.txt","r")) == NULL) {


puts("File could not be opened.");

}

else {

unsigned int account;
char name[30];
double balance;

printf("%-10s%-13s%s\n", "Account", "Name", "Balance");
fscanf(cfPtr, "%d&29s%lf", &account, name, &balance);


while(!feof(cfPtr)) {

printf("%-10d%-13s%7.2f\n", account, name, balance);
fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);

}

fclose(cfPtr);
}

return 0;

}

文件内容:

1 John 45.54        
2 Mike 56.65
3 Patrick 23.32

写入程序的输入:
Inputs of the writing program

读取程序的输出:
Output of the reading program

我复制了《C 如何编程》书籍第 8 版中的代码。

这里出了什么问题?

最佳答案

(代表 OP 发布)

我没有使用调试器,所以我找不到可以这样解决的小错误:

"%d&29s%lf" -> "%d%29s%lf"

进行更改后,我得到了正确的结果。

关于c程序无法正确读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127496/

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