对于像fgets/scanf这样将结构指针指定给值的输入函数真的很困惑吗
关于使用输入函数(如fgets/scanf)将结构指针指定给值,下面的部分确实很难理解 此代码希望实现的是:对于像fgets/scanf这样将结构指针指定给值的输入函数真的很困惑吗,c,structure,C,Structure,关于使用输入函数(如fgets/scanf)将结构指针指定给值,下面的部分确实很难理解 此代码希望实现的是: 测试用例1: 输入姓名(firstName lastName): 詹姆斯·林 输入帐号: 123 输入余额: 6789.89 客户记录:James Lim 123 6789.89 输入姓名(firstName lastName): 最终客户您忘了问问题……我假设您的代码没有达到您预期的效果,但您忘了告诉我们出了什么问题。顺便说一句:永远不要使用%sinscanf缓冲区溢出的大怪物会缠着您
测试用例1:
输入姓名(firstName lastName):
詹姆斯·林
输入帐号:
123
输入余额:
6789.89
客户记录:
James Lim 123 6789.89
输入姓名(firstName lastName):
最终客户您忘了问问题……我假设您的代码没有达到您预期的效果,但您忘了告诉我们出了什么问题。顺便说一句:永远不要使用
%s
inscanf
缓冲区溢出的大怪物会缠着您。(提示:%9s
)scanf(“%f”,账户->余额)
导致未定义的行为acct->balance
是一个double
,这意味着您需要使用%lf
格式说明符<代码>%f表示浮动
。如果您遵循“将所有警告视为错误”的简单规则,您可以在10秒内解决此问题
#include <stdio.h>
#include <string.h>
struct account
struct
{
char lastName[10];
char firstName[10];
} names;
int accountNum;
double balance;
};
void nextCustomer(struct account *acct);
void printCustomer(struct account acct);
int main()
{
struct account record;
int flag = 0;
do {
nextCustomer(&record);
if ((strcmp(record.names.firstName, "End") == 0) &&
(strcmp(record.names.lastName, "Customer") == 0))
{
flag = 1;
}
if (flag != 1)
{
printCustomer(record);
}
} while(flag != 1);
}
void nextCustomer(struct account *acct)
{
int i;
char temporary[20];
printf("Enter names (firstName lastName) :\n");
scanf("%s", acct->names.firstName);
scanf("%s", acct->names.lastName);
printf("Enter account number: \n");
scanf("%d", acct->accountNum);
printf("Enter balance: \n");
scanf("%f", acct->balance);
}
void printCustomer(struct account acct)
{
printf("%s %s %d %.2lf", acct.names.firstName, acct.names.lastName, acct.accountNum, acct.balance);
}