cpointersstructoperatorsgets

taking input using gets with arrow operator not working? What's the Error?


What's the Error in this ? I tried taking input using arrow operator.

#include <stdio.h>

typedef struct{
  char name[100];
  int salary;
}emp;

void inp(emp *e){
  printf("enter name : ");
  gets(e->name);
  printf("enter salary : ");
  scanf("%d", e->salary);
}
int main() {
    emp *e1,*e2;
    inp(e1);
    inp(e2);
    printf("%s , %d\n", e1->name,e1->salary);
    printf("%s , %d\n", e2->name,e2->salary);
  return 0;
}

I tried putting & and even giving inp function as emp but it doesn't work. It just asking me 1st employee name. dat's it! Not even printing Enter salary. What changes should I make?


Solution

  • Your struc have been created wrong. So i changed your code like this to make it clear. I also did use getchar() function so you can call fget() function multiplie times. I guess it does work like you wish.

    #include <stdio.h>
    
    struct Emp{
      char name[100];
      int salary;
    };
    
    void func(struct Emp *e){
      printf("enter name : ");
      fgets(e->name, sizeof(e->name), stdin);
      printf("enter salary : ");
      scanf("%d", &e->salary);
      getchar();
    }
    int main() {
        struct Emp e1,e2;
        func(&e1);
        func(&e2);
        printf("\n%s , %d", e1.name,e1.salary);
        printf("\n%s , %d", e2.name,e2.salary);
      return 0;
    }