I’m new to programming and have been working on an assignment in class. For some strange reason the program keeps printing 2 different printf’s on the same line and not giving me a chance to input information
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{ char Name[20];
char cid1[6]="", cid2[6]="", cid3[6]="", cid4[6]="", cid5[6]="", cid6[6]="";
char Description1[21]="", Description2[21]="", Description3[21]="", Description4[21]="", Description5[21]="", Description6[21]="";
int hrs1 = 0, hrs2=0, hrs3=0, hrs4=0, hrs5=0, hrs6=0;
char grade1[2]="",grade2[2]="",grade3[2]="",grade4[2]="",grade5[2]="",grade6[2]="";
printf("Enter Students Name ");
fgets(Name, 20, stdin);
printf("Enter Class ID ");
scanf("%5s", cid1);
printf("Enter Class Description "); // Problem
fgets(Description1, 20, stdin); // here
printf("Enter Class Hours ");
scanf("%d", &hrs1);
printf("Enter Class Grade ");
fgets(grade1, 1, stdin);
printf("%s\n", Name);
printf("%s\n", cid1);
printf("%s\n", Description1);
printf("%d\n", hrs1);
printf("%s\n", grade1);
system("pause");
return 0;
The area marked “Problem here” is where the problem is currently occurring. In stead of prompting for the class description it will skip straight to entering class hours and completely ignore the enter class grade at the bottom.
It prints it as: Enter Class DescriptionEnter Class Hours.
They are trying to teach you the difference between
scanfandfgets. And they are probably tricking you by telling you that the Class ID has to be 4 characters.So if your Class ID is “1234” and you hit Enter after, what ends up in
stdinis:1234\r\nThe
%5sformat inscanfsays to read 5 characters and then move on. So, you read in1234\rand leave\nin thestdinstream. Then whenfgetsexecutes, it reads in the\nand moves on.From the above on
fgets: