2

I have tried this code for printing some persons' basic information. Here is the code :

#include <stdio.h>

struct person {
    char name[100];
    int age;
    float salary;
};

int main() {
    struct person p[3];
    int i;
    for(i=0;i<3;i++){
        printf("Enter informations for person no %d:\n\n",i+1);
        printf("Enter name : \n");
        gets(p[i].name);
        printf("Enter age : \n");
        scanf("%d",&p[i].age);
        printf("Enter salary : \n");
        scanf("%f",&p[i].salary);
    }
    for(i=0;i<3;i++){
        printf("\n\nInformations for person no %d:\n\n",i+1);
        printf("Name: %s\n",p[i].name);
        printf("Age : %d\n",p[i].age);
        printf("Salary : %0.2f\n",p[i].salary);
    }
    return 0;
}

Now while scanning data, this code takes only takes all the information of first person and doesn't take character type data of others.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Maria
  • 67
  • 1
  • 3
  • 7

1 Answers1

1
  1. I would recommend using fgets() instead of gets() because gets can be dangerous (In order to use gets() safely, you have to know exactly how many characters you will be reading, so that you can make your buffer large enough). fgets() also takes the '\n' char at the end, in order to prevent this you can write the following line: p[i].name[strlen(p[i].name)-1] = '\0';

  2. Your main problem is that salary input leaves '\n' character, and you need to collect it with getchar();

So you need to write something like this:

#include <stdio.h>
#include <string.h>

struct person {
    char name[100];
    int age;
    float salary;
};

int main() {
    struct person p[3];
    
    int i;
    for(i=0;i<3;i++){
        printf("Enter informations for person no %d:\n\n",i+1);
        printf("Enter name : \n");
        fgets(p[i].name,100,stdin);
        p[i].name[strlen(p[i].name)-1] = '\0';
        printf("Enter age : \n");
        scanf("%d",&p[i].age); 
        printf("Enter salary : \n");
        scanf("%f",&p[i].salary); 
        getchar();
    }
    
    for(i=0;i<3;i++){
        printf("\n\nInformations for person no %d:\n\n",i+1);
        printf("Name: %s\n",p[i].name);
        printf("Age : %d\n",p[i].age);
        printf("Salary : %0.2f\n",p[i].salary);
    }
    
    return 0;
}
Majkl
  • 153
  • 1
  • 7