结构,使用指针和函数来存储和检索数据


struct account
{
struct //A structure inside a structure
{
char lastName[10];
char firstName[10];
} names; //structure is named as 'name'
int accountNum;
double balance;
};
int main()
{
struct account record;
int flag = 0;
do
{
nextCustomer(&record);
if ((strcmp(record.names.firstName, "End") == 0) && //only when the first name entered as "End"
(strcmp(record.names.lastName, "Customer") == 0)) //and last name entered as "Customer", the loop stops
flag = 1;
if (flag != 1)
printCustomer(record);
}
while (flag != 1);
}
void nextCustomer(struct account *acct)
{
printf("Enter names (firstName lastName):n"); 
//scanf("%s, %s", acct->firstName, acct->lastName); //have no idea why first and last name cant be found although im aware thats its a structure inside a structure
printf("Enter account number:n");
//scanf("%d", acct->accountNum); 
printf("Enter balance:n");
scanf("%f", acct->balance);
}
void printCustomer(struct account acct)
{
printf("Customer record: n");
printf("%d", acct.accountNum); //can't seem to retrieve data from the strcture
}

大家好,我是c的新手,我设法对结构上的数据进行了硬编码,并打印了它们各自的值。目前,我正在使用指针来存储各自的数据,以及打印出数据的函数。有人能帮我解释为什么我不能存储和检索我的数据吗?我不需要答案,只要逻辑流程就足够了。

如果您的nextCustomer函数需要更改,您可以使用acct直接访问firstNamelastName,但它们存在于names

所以你必须使用acct->names.firstNameacct->names.lastName

void nextCustomer(struct account *acct)
{
printf("Enter names (firstName lastName):n"); 
scanf("%s%s", acct->names.firstName, acct->names.lastName); //have no idea why first and last name cant be found although im aware thats its a structure inside a structure
printf("Enter account number:n");
scanf("%d", &acct->accountNum); 
printf("Enter balance:n");
scanf("%lf", &acct->balance);
}
void printCustomer(struct account acct)
{
printf("Customer record: n");
printf("F: %sn", acct.names.firstName);
printf("L: %sn", acct.names.lastName);
printf("A: %dn", acct.accountNum); //can't seem to retrieve data from the strcture
printf("B: %lfn", acct.balance);
}

最新更新