cstringgets

Why is gets() not consuming a full line of input?


I'm trying to use gets() to get a string from the user, but the program seems to be passing right over gets(). There is no pause for the user to give input. Why is gets() not doing anything?

char name[13];
printf("Profile name: ");
gets(name);
printf("\n%s", name);

Solution

  • You get lot of troubles using gets()

    Instead go for fgets()

    fgets(name,13,stdin);  
    

    See this SO question Why is the gets function so dangerous that it should not be used?

    The reason why fgets() does not work, may be you are not handling the newline left behind by scanf in your previous statements.

    You can modify your scanf format string to take it into account: scanf("%d *[^\n]", &N);

    *[^\n] says to ignore everything after your integer input that isn't a newline, but don't do anything with the newline (skip it).

    When you use scanf("%d",&num) you hit 13 and enter and 13 is stored in num and the newline character is still in the input buffer when you read fgets from stdin it treats \n as the data you have entered and the fgets() statement is skipped

    You cannot flush input buffer however you can do this fseek(stdin,0,SEEK_END); add this before your every fgets statement