1

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);
       }
JWH_
  • 267
  • 2
  • 12

1 Answers1

1
  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

Community
  • 1
  • 1
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • Ah i see! Does that mean I should add "&" for the string scanf too? But why is it working fine without it? – JWH_ Sep 20 '15 at 19:09
  • When you pass a string to a function it decays to a pointer. e.g. `acct->names.firstName` appears to be of type `char*`. So you don't have to and shouldn't use & for the string. But be aware of the size of the buffer, if it's big enough for the input. – Manos Nikolaidis Sep 20 '15 at 19:11