【发布时间】:2021-09-28 16:37:06
【问题描述】:
创建一个结构来指定银行客户的数据。要存储的数据是:账号、姓名、账户余额。假设银行中最多有 200 名客户。
struct CustomerData {
int acNum;
float balance;
char name[];
} n[2];
void main() {
for(int i = 0;i<2; i++) {
printf("give Ac. no. of %d customer\n",i+1);
scanf("%d",&n[i].acNum);
printf("balance of customer %d\n",i+1);
scanf("%f",&n[i].balance);
printf("Name of customer %d\n",i+1);
fflush(stdin);
gets(n[i].name);
}
printf(" Name Acc. no Balance \n");
for(int i =0;i<2;i++) {
printf("%c %d %f\n",puts(n[i].name),n[i].acNum,n[i].balance);
}
}
输出:
give Ac. no. of 1 customer
50054
balance of customer 1
11316
Name of customer 1
sahil
give Ac. no. of 2 customer
15655
balance of customer 2
100
Name of customer 2
Rishav
Name Acc. no Balance
'=
50054 11316.000000
Rishav
15655 100.000000
Process returned 34 (0x22) execution time : 25.120 s
Press any key to continue.
【问题讨论】:
-
fflush在输入流上调用未定义的行为,gets(n[i].name);不仅是错误的,因为它使用的是标准库中不再存在的函数,更糟糕的是它针对的是一个灵活的数组成员,它没有“那里”在那里。无论什么书/网站教这个,烧掉它。 -
为什么要打印
puts的结果?您似乎错过了初学者教科书前几章的一些关键部分。如果你没有书,请买一本。 -
你的结构中的the flexible array member
name不是动态数组。没有为它分配空间。你真的需要一本像样的初学者书,从一开始就开始阅读。不管你目前用来学习 C 的任何资源,都扔掉。 -
Sahil Dadhwal,允许的最长名字是多少? 600+ letters?
-
Sahil Dadhwal,我建议放弃
scanf()。使用fgets()将用户输入的每一行读入一个字符串,然后解析该字符串。
标签: arrays c string for-loop struct