marc jose
marc jose

Reputation: 27

How to use members of a structure for arithmetic operators (add,sub,mul,div a variable to a struct member)

Sorry for the noob question. How do i use arith operators to variables within the structure?

I have this struct

struct account {
    int no;
    char name[100];
    int pin;
    float id;
}; 

what I want to do is add a value to float id

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <process.h>

main() {
    struct account {
        int no;
        char name[100];
        int pin;
        float id;
    }; 
    struct account rec;
    float i;
    printf("enter var value \n");
    scanf("%f", &i);

    printf("enter value to struct\n");
    scanf("%f", &rec.id);

    rec.id = rec.id + i;

    printf("sum is %0.2f", rec.id);
}

the value of rec.id stays the same.

I know I'm missing something. hopefully it wouldn't be too much of a bother

Upvotes: 1

Views: 105

Answers (1)

Ctx
Ctx

Reputation: 18420

The format specifiers of scanf() differ from those of printf(). Especially the length of the decimals cannot be given there, so the flags 0.2 to %f are invalid. Just use

scanf("%f",&i);

printf("enter value to struct\n");
scanf("%f",&rec.id);

As Jonathan Leffler noted, it is however possible to specify the total length of the number (including dot and decimals), for example with %4f to scan for a four character decimal.

Furthermore, you should enable all compiler warnings and listen to them. You would have observed warnings, which show up this exact problem.

Additionally, you should check the return values of scanf() to see, if the conversions succeeded. Otherwise, the values in your variables remain uninitialized.

Two minor issues:

  • Use int main (void)
  • Explicitly return a value from main() or call exit(0) (not strictly needed anymore if you use at least the C99 standard)

Upvotes: 4

Related Questions