【问题标题】:Getting User Input and storing into elements in Structure获取用户输入并存储到结构中的元素中
【发布时间】:2015-09-20 18:58:44
【问题描述】:

我目前正在编写一个简单的代码,它重复读取用户输入并将输入存储到一个结构中,然后将它们打印出来。我在阅读“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. 获取int 和double

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

      &amp;acct-&gt;accountNum 是指向int 的指针,并且 &amp;acct-&gt;balance 是指向 double 的指针

    2. 在第二个scanf 中你忘记了'%'。

    3. 不建议将gets() 用于任何目的,它现在被视为已弃用的功能。阅读更多here

    【讨论】:

    • 啊,我明白了!这是否意味着我也应该为字符串 scanf 添加“&”?但是为什么没有它也能正常工作呢?
    • 当您将字符串传递给函数时,它会衰减为指针。例如acct-&gt;names.firstName 似乎属于 char* 类型。因此,您不必也不应该将 & 用于字符串。但请注意缓冲区的大小,如果它足够大以容纳输入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2017-06-25
    • 1970-01-01
    • 2019-09-10
    相关资源
    最近更新 更多