scanfgetsputs

Puts() and Gets() does not work when used after scanf()


It seems that the puts() and gets() functions do not work if I use scanf() before gets() and puts(). Please see code below.

If I delete the section before, puts() and gets() work okay. Why is that?

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

int main (void)
{
    int numberOutcomes;
    char outcomeOne[50];

    printf("How many outcomes do you have on your form?\n");
    scanf(" %d", &numberOutcomes);
    printf("The number of outcomes you have on your form is %d\n", numberOutcomes);

    printf("Type in your first outcome then press Enter. For example: good outcome or bad outcome.\n");
    gets(outcomeOne);

    puts(outcomeOne);

    return 0;
}

Solution

  • First piece of advice, don't use gets() - there is no way to use it safely so as to avoid potential buffer overflow (it's one of the few things that have even been removed from the ISO standard, as of C11). Instead, use fgets(), which can limit what's read in.

    As to your specific problem, scanf(" %d", &numberOutcomes) will, after skipping whitespace, consume enough characters in the input stream to populate numberOutcomes, and no more. Importantly, it will not consume trailing whitespace such as the \n character that was put there when you pressed ENTER to submit your input.

    Hence, on the gets() call, it will simply get a blank line.

    Both of those problems can be solved in you choose either the scanf()-style input or line-based input. For the former case, scanning the next item will (usually) skip the whitespace in the input stream, for the latter, reading lines reads the whole line including trailing whitespace.

    You can make it work by mixing the two but it's a bit more effort.

    My advice would be to use line-based input for everything and then sscanf specific data out of the string you read. This has the advantages of:

    For that, a rock-solid line-input routine (like this one) is very handy.