我编写了这段代码,但它给出了分段错误。该循环仅适用于printf语句。请帮我纠正这个问题。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *fp;
int n,i;
typedef struct transactions
{
char bank_name;
int amount;
int time; //to be given in the form:1320
char location;
int acc_no;
}transaction;//structure
transaction t;
void main()
{
printf("\nHow many records you would like to insert ? : ");
scanf("%d",&n);
fp=fopen("input.txt","r+");
for(i=0;i<n;i++)
{
printf("\nEnter the transaction details");
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
fwrite(&t,sizeof(t),1,fp);
}
fclose(fp);
}
答案 0 :(得分:2)
bank_name
和location
不是字符串,而是单个字符。但是您尝试使用%s
将字符串存储在其中。因此程序会崩溃并烧毁。
答案 1 :(得分:0)
编译时应该激活警告...
% clang testt.c -Wall
testt.c:22:1: warning: return type of 'main' is not 'int' [-Wmain-return-type]
void main()
^
testt.c:30:28: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
~~ ^~~~~~~~~~~
testt.c:30:58: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
~~ ^~~~~~~~~~
3 warnings generated.
% gcc testt.c -Wall
testt.c:22:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
void main()
^
testt.c: In function ‘main’:
testt.c:30:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
^
testt.c:30:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 5 has type ‘int’ [-Wformat=]
我相信你可以自己解决问题(错误的类型)。