I am a newbie in C. Consider my following code:
#include <stdio.h>
#include <string.h>
int main()
{
char strs[5][6];
char temporary[5]="";
for(int i=0;i<5;i++)
{
fgets(temporary,6,stdin);
if(strlen(temporary)>5)
temporary[strlen(temporary)-1]='';
strcpy(strs[i],temporary);
}
printf("%s donen",strs[0]);
printf("%s donen",strs[1]);
printf("%s donen",strs[2]);
printf("%s donen",strs[3]);
printf("%s donen",strs[4]);
return 0;
}
The question may have probable duplicates, but I could not find one. Now, I have come across some confusions. First of all, the line temporary[strlen(temporary)-1]='';
erases off the final character in the string. So if the user inputs n
, then fgets()
encounters the newline character [for the sake of clarity, consider that the character length has never been 5 in any of these inputs, it’s always been 4]. Then, here is an output that I receive:
In case the input is: Barn
I could never go to the next line pressing Enter. Moreover, the output for all inputs being five letter is even more horrible.
Dhaka Pabna Tales
gives the output:
`
done
done
Pabna done
done
Tales done
`
No idea what has happened. I just want only five characters to be taken as input. If user input is of four characters, the newline is received and stored as a character, whereas, if it is of five letters, it shall remain as it is. So, what I am missing?
2