获取用户输入并将其存储到结构中的元素中

问题描述 投票:0回答:1

我目前正在编写一个简单的代码,该代码重复读取用户输入并将输入存储到结构中,然后将其打印出来。我在读取“accountNum”和“balance”时遇到问题。编译器给出的警告是由于预期参数的类型不同所致。 (*int/*double 与 int/double)。 我尝试使用 gets() 但无济于事。我希望对此有所了解。

另外,我在打印功能期间是否正确访问了元素?预先感谢!

#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)
{
    printf("Enter names: (firstName lastName): " );
    scanf("%s%s", acct->names.firstName, acct->names.lastName);
    printf("Enter account number: ");
    scanf("%d", &acct->accountNum);
    printf("Enter balance : ");
    scanf("%lf", &acct->balance);
}

void printCustomer(struct account acct)
{
    printf("%s%s %d %lf", acct.names.firstName, acct.names.lastName ,acct.accountNum,acct.balance);
}
c pointers structure
1个回答
1
投票
  1. 获取

    int
    double

    scanf("%d", &acct->accountNum);
    scanf("%lf", &acct->balance);
    

    &acct->accountNum
    是指向
    int
    的指针并且
    &acct->balance
    是指向
    double

  2. 的指针
  3. 在第二个

    scanf
    你忘记了
    '%'

  4. 不建议将

    gets()
    用于任何目的,它现在被认为是已弃用的函数。阅读更多这里

© www.soinside.com 2019 - 2024. All rights reserved.