cpointersstructure

Getting User Input and storing into elements in Structure


I am currently writing a simple code that repeatedly reads user input and store the input into a structure, subsequently printing them out. I encounter a problem while reading "accountNum" and "balance". The warning the compiler gave was due to the type of different arguments expected. (*int/*double vs int/double). I tried using gets() but to no avail. I am hoping to get an understanding on this.

Also, am I accessing the elements correctly during the print function? Thanks in advance!

#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);
}

Solution

    1. To get the int and the double

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

      &acct->accountNum is a pointer to int and &acct->balance is a pointer to double

    2. In the second scanf you had forgotten '%'.

    3. It is not recommended to use gets() for any purpose and it is now considered a deprecated function. Read more here