I'm fairly new to C and I have this program, and whenever I execute it, I get a weird output, like if fgets was bypassing and taking priority over printf and scanf
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct object {
float weight;
char name[30];
char utility[30];
};
int main()
{
struct object *ptr;
int i, n;
printf("Enter the number of objects: ");
scanf("%d", &n);
ptr = (struct object*) malloc(n * sizeof(struct object));
for(i = 0; i < n; ++i)
{
printf("Enter name: ");
scanf("%s\n", (ptr+i)->name);
printf("Enter weight: ");
scanf("%f\n", &(ptr+i)->weight);
printf("Enter Utility: ");
fgets((ptr+i)->utility, 30, stdin);
(ptr+i)->utility[strlen((ptr+i)->utility)-1] = '\0';
}
printf("\nDisplaying Information:\n");
for(i = 0; i < n; ++i)
printf("Name: %s\tUtility: %s\tWeight: %0.1f\n", (ptr+i)->name, (ptr+i)->utility, (ptr+i)->weight);
return 0;
}
Output
Enter the number of objects: 1
Enter name: name
utility
Enter weight: Enter Utility:
Displaying Information:
Name: name Utility: utility Weight: 0.0
I've tried what suggested in fgets() not waiting for input but nothing worked, even printing to stderr.
EDIT: I've manage to fix it the following way. Thanks for the help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct object {
float weight;
char name[30];
char utility[30];
};
int main()
{
struct object *ptr;
int i, n;
printf("Enter the number of objects: ");
scanf("%d", &n);
ptr = (struct object*) malloc(n * sizeof(struct object));
for(i = 0; i < n; ++i)
{
printf("Enter name: ");
scanf("%s", &ptr[i].name);
printf("Enter weight: ");
scanf("%f", &ptr[i].weight);
while ((getchar()) != '\n');
printf("Enter Utility: ");
fgets(ptr[i].utility, 30, stdin);
ptr[i].utility[strlen(ptr[i].utility)-1] = '\0';
}
printf("\nDisplaying Information:\n");
for(i = 0; i < n; ++i)
printf("Name: %s\tUtility: %s\tWeight: %0.1f\n", ptr[i].name, ptr[i].utility, ptr[i].weight);
return 0;
}