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

时间:2020-11-11 17:46:00

标签: c

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语言的新手,我设法对结构上的数据进行硬编码,并打印出它们各自的值。目前,我正在使用指针存储相应的数据,以及打印其数据的功能。谁能帮助我为什么我不能存储和检索我的数据?我不需要答案,只是逻辑流程就足够了。

1 个答案:

答案 0 :(得分:1)

需要对nextCustomer函数进行以下更改,您正在使用firstName直接访问lastNameacct,但是它们位于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: %s\n", acct.names.firstName);
    printf("L: %s\n", acct.names.lastName);
    printf("A: %d\n", acct.accountNum); //can't seem to retrieve data from the strcture
    printf("B: %lf\n", acct.balance);
}