1

When I put "four" in after the first printf, then I can't write in the second printf.

Why does this happen?

#include <stdio.h>
#include <string.h>

int main() {
    char buffer[5]= {0};
    char buffer2[5]= {0};

    printf("Put your name: "); //i put four
    fgets(buffer,sizeof(buffer),stdin);
    size_t len = strlen(buffer)-1;

    if (buffer[len] == '\n')
        buffer[len] = '\0';

    printf("Put your second name: ");
    fgets(buffer2,sizeof(buffer2),stdin);
    printf("%s",buffer2);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
jhonnna
  • 107
  • 5
  • Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane May 30 '18 at 22:05
  • 1
    Perhaps your first and second names are longer than 3 characters (5 to include newline and string terminator). If the first is longer, the excess won't be thrown away but read into the second `fgets`. Don't be mean with your buffer size. – Weather Vane May 30 '18 at 22:07
  • As I understand it you are entering a 4-character name first, such as **four** and so as the buffer has only 5 (incl terminator) the trailing newline is read as the second input, so of course the second `printf` does not show anything. – Weather Vane May 30 '18 at 22:26
  • 1
    `size_t len = strlen(buffer)-1;` strlen() can return zero. – wildplasser May 30 '18 at 23:08

1 Answers1

1

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`
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256