Chetan Pujar Chetan Pujar - 3 months ago 9
C Question

Second and the third gets() function in C are not working

The compiler does not show any error but the second and the third

gets()
functions do not seem to work as expected. Instead the next line of code gets executed.

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

struct student {
char name[100], result[100];
int marks;
} s1, s2, s3;

main() {
printf("Enter the name of the student s1:");
gets(s1.name);
printf("Enter the marks obtained by the student s1:");
scanf("%d", &s1.marks);
printf("Enter the name of the student s2:");
gets(s2.name);
printf("Enter the marks obtained by the student s2: ");
scanf("%d", &s2.marks);
printf("Enter the name of the student s3:");
gets(s3.name);
printf("Enter the marks of the student s3:");
scanf("%d", &s3.marks);
if ((s1.marks > s2.marks) & (s1.marks > s3.marks))
printf("the student s1 has got the highest marks");
else
if ((s2.marks > s3.marks))
printf("The student s2 has got the highest marks");
else
printf("The student s3 has got the highest marks");
}


enter image description here

Answer

This is because you are mixing up gets (which is deprecated*) and scanf.

End-of-line mark from scanf remains in the buffer, so when gets tries to read the next input, it treats it as an empty line.

You can fix this by using scanf for all your input, including strings:

printf("Enter the name of the student s1:");
scanf("%99s", s1.name); // Use "%99[^\n]" to allow multi-part names
printf("Enter the marks obtained by the student s1:");
scanf("%d", &s1.marks);

* gets is deprecated, so you should use fgets(s1.name, sizeof(s1.name), stdin) instead. Here is a reference for fgets.