0

I'm I complete newbie and I found out about fgets only last night! I used it and seemed to have worked the first time but skips the code on the second string.

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

int main() {
    char name[100];
    char address[500];
    int age;

    printf("Input your personal details\n");

    printf("Name: ");
    fgets(name, 100, stdin);
    name[strlen(name)-1] = '\0';

    printf("Age: ");
    scanf("%d", &age);

    printf("Address: ");
    fgets(address, 500, stdin);
    address[strlen(address)-1] = '\0';

    printf("\nHello, %s, how are you?\n", name);
    printf("%d\n", age);
    printf("%s", address);
    
return 0;
}

The output is then

Name: Taylor Swift
Age: 18
Address: 
Hello, Taylor Swift, how are you?
18
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Llrence
  • 17
  • 1
  • 2
    Does this answer your question? [scanf() leaves the newline character in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer) – Klas-Kenny Jan 03 '22 at 13:28
  • 1
    Don't mix `fgets()` (and/or `getchar()`) with `scanf()`. Either always use only `fgets()` or use only `scanf()` ... `fgets()` is way better – pmg Jan 03 '22 at 13:34

1 Answers1

-1

Add a getchar() before the second fgets(), this worked for me. I apologise if this is not "the correct way" I am still learning too

pion
  • 34
  • 5
  • That sorts of works, but only if there are no trailing blanks after the age. It is better to use a loop that reads to the next newline: `int c; while ((c =getchar()) != EOF && c != ‘\n’) ;` for example. – Jonathan Leffler Jan 03 '22 at 13:45