I had to write an assignment in C, where we had to define a structure and perform some operations on it. This is the code I have written:
#include <stdio.h>
struct student {
char name[100];
int roll_no;
int chem, phy, math, total;
};
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct student s[n];
for(int i = 0; i < n; i++) {
printf("Enter the name of the student: ");
gets(s[i].name);
printf("Enter the roll number of the student: ");
scanf("%d", &s[i].roll_no);
printf("Enter the marks of phy, chem and maths: ");
scanf("%d %d %d", &s[i].phy, &s[i].chem, &s[i].math);
s[i].total = s[i].phy + s[i].chem + s[i].math;
}
printf("\n\nMerit List\n");
printf("Rank \tName \tRollno \tPhy \tChem \tMaths \tTotal\n");
for(int i = 0; i < n; i++) {
printf("%d \t%s \t%d \t%d \t%d \t%d \t%d\n", i + 1, s[i].name, s[i].roll_no, s[i].phy, s[i].chem, s[i].math, s[i].total);
}
return 0;
}
When I compile and run this function, I am not able to input the values properly. I am not even seeing the input message properly, as this is the input message.
Enter the number of students: 2
Enter the name of the student: Enter the roll number of the student: skdjk 3
Enter the marks of phy, chem and maths: Enter the name of the student: Enter the roll number of the student: 3 4 6 dskj 2
Enter the marks of phy, chem and maths:
which was not what I expected. The output is also weird as I'm getting this:
Merit List
Rank Name Rollno Phy Chem Maths Total
1 32764 32700 1416183288 32768 1416248756
2 skdjk 3 1 3 3 4 6 -1028599268 -1028599258
When I took the string input using scanf, the issue is being resolved. Why does gets(and even fgets) cause these problems? How to resolve them?
gets? Did you see the part that says "Never usegets()" and to "Usefgets()instead"?gets()immediately. It's a dangerous function because you can't specify the buffer size, and it has been removed from the language. Usefgets()instead.gets()has been removed from c11: stackoverflow.com/a/34031565/2666293 Your problem may be the compiler is just ignoring the call to gets