下面的代码将要求输入,并应该在之后打印它。
然而,我遇到了几个问题。
问题
- 程序在我确认输入后停止工作。
- 当它应该打印输入时,却打印出了奇怪的符号。
问题:
如何打印变量的全部值?
For ex :- 当我输入“John Lemon”时它要求输入“Name:”。
我可以打印“John Lemon”而不是“John”。打印完变量的第一个值后,如何继续完整打印变量的第二个值和第三个值?
对于 ex:
示例输出
姓名:John Lemon
年龄:21岁
地址:41, 2/2 Apple Street
如何解决这个问题?
如果可能,请用通俗易懂的语言解释一下,因为我是 C 编程的新手。
抱歉,如果这看起来很乱。我已尽力使其尽可能简单。
#include<stdio.h>
char fname[]={"guest.dat"};
struct text
{
char name;
int age;
char address;
};
void printing ()
{
struct text t1;
FILE *fp;
fp=fopen(fname,"r");
printf("\nName: %c",t1.name);
printf("\nAge: %d",t1.age);
printf("\nAddress: %s",t1.address);
}
int main ()
{
FILE *fp;
int choice;
struct text t1;
fp=fopen(fname,"a+");
fread(&t1,sizeof(t1),1,fp);
printf("\nPlease enter name: ");
scanf("%c",&t1.name);
fflush(stdin);
printf("\nPlease enter age: ");
scanf("%d",&t1.age);
fflush(stdin);
printf("\nPlease enter address: ");
scanf("%s",&t1.address);
fflush(stdin);
printf("\nConfirm? (Y/N): ");
scanf("%c",&choice);
if ( choice == 'y' | choice == 'Y')
{
fp=fopen(fname,"a+");
fwrite(&t1,sizeof(t1),1,fp);
fclose(fp);
fflush(stdin);
system("cls");
printing();
}
else if ( choice == 'n' | choice == 'N')
{
fflush(stdin);
system("cls");
printing();
}
else
fflush(stdin);
system("cls");
printf("Please try again!");
system("pause");
}
最佳答案
您的程序打印“奇怪的符号”,因为 t1
从未在 printing
函数中初始化。
在这里你永远不会从文件中读取:
void printing ()
{
struct text t1;
FILE *fp;
fp=fopen(fname,"r");
// Missing read from file
printf("\nName: %c",t1.name);
printf("\nAge: %d",t1.age);
printf("\nAddress: %s",t1.address);
}
此外,这一行:
printf("\nAddress: %s",t1.address);
错了。您使用 %s
用于 char*
但 address
是 char
。所以你必须使用%c
。 address
的scanf
也是如此。
也许你真的想要 struct text
来保存字符串!?如果是这样,您应该使用 char array
。目前该结构只能保存字符(即名称和地址的单个字母)。也许你真的想做:
struct text
{
char name[100];
int age;
char address[100];
};
然后对 printf
和 scanf
使用 %s
而不是 %c
。
这里还有一些“奇怪”的代码:
int main ()
{
FILE *fp;
int choice;
struct text t1;
// Why do you have the next to lines? Seems to be a mistake - remove them
fp=fopen(fname,"a+");
fread(&t1,sizeof(t1),1,fp);
除此之外,您的代码缺少对返回值的各种检查。始终检查 fopen
、fread
、fwrite
和 scanf
返回的值。
关于c - 数据保存和数据读取(C编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39909640/