When I put "four" in after the first printf, then I can't write in the second printf.
The user is not only typing four, but also enter. So the true line of input is 5 characters of "four\n"
.
The following code will only read 4 characters into buffer[5]
, leave the '\n"
in stdin
for the next fgets()
. fgets()
read one less than 5 to leave room for the appended null character.
char buffer[5]= {0};
fgets(buffer,sizeof(buffer),stdin);
Avoid too small a buffer, instead recommend 2x the largest expected size. E.g. longest name
#define NAME_MAX 585
#define BUF_SIZE ((NAME_MAX + 1 /* \n */ + 1 /* \0 */)*2)
char buffer[BUF_SIZE] = {0};
printf("Put your name: ");
if (fgets(buffer,sizeof buffer,stdin)) {
// process buffer only if `fgets()` succeeds
Avoid a hacker exploit. The following is certainly UB should the nefarious user enter a null character as the first character. Ctrl @ourenter.
size_t len = strlen(buffer)-1;
if (buffer[len] == '\n')
Instead
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
buffer[--len] = '\0';
}
// Now use `buffer and `len`