I’ve wrote a program that gets from the user a number, and then gets from the user a name for every number…
for example if the user entered the number 10, it’d take 10 names and put it in an array of structs…
Everything is working great, except that when I print the names, it skip’d the first letter…
like if I put in the name “Amit”, it printed “mit”… , also, the last string I’ve entered didnt save at all..
Here is what I wrote :
const number_candidates; // Getting the number of candidates
#define MAX 256
#define min_candidate 10
#define max_candidate 60000
typedef struct candidate // Getting details for each candidate
{
char name[MAX];
int sing_grade;
int per_grade;
int cam_grade;
int sharmanti_grade;
}candidate;
void get_details_candidates(candidate candidate[MAX])
{
int i = 0;
printf ("\n");
for (i = 0 ; i < number_candidates ; i++)
{
printf ("Please enter the %d name: ", i + 1);
fgets (candidate[i].name, MAX, stdin);
getchar();
}
}
Here is the printing:
for (i = 0 ; i < number_candidates ; i++)
{
printf ("%s\n", candidates[i].name);
}
Thanks for your help!
The
getchar()after thefgets()is eating the first letter of the following line.Your problem reading the first name may be caused by a stray newline in the input stream. To flush
stdinbefore your input loop you can use something like this:I think
fflush(stdin)is undefined behaviour so don’t do that.