Program doesn't execute gets() after scanf(), even using fflush(stdin)

后端 未结 5 1560
不思量自难忘°
不思量自难忘° 2020-12-01 22:54

After wasting too much time searching why my program doesn\'t execute gets() after using scanf(), I found a solution which is to use fflush(stdin) after scanf() to enable ge

5条回答
  •  独厮守ぢ
    2020-12-01 23:34

    Two big, major issues:

    1. DO NOT USE fflush ON INPUT STREAMS; the behavior of fflush on input streams is not defined. Just because it appears to work in this situation does not mean it is correct.

    2. NEVER NEVER NEVER NEVER NEVER NEVER NEVER use gets - it was deprecated in the C99 standard and has been removed completely from the C2011 standard. It will (not might, will) introduce a major point of failure in your code.

    It's never a good idea to follow a scanf call with a gets call, since gets won't skip over any leading newlines left in the input stream by scanf. Use scanf to read both nombre and mesaje.

    printf("Type your name:\n");
    scanf("%9s", nombre);
    
    printf("Now, type a message:\n");
    scanf("%79s", mensaje);
    

    It's a good idea to use an explicit length specifier in the scanf call for %s and %[, otherwise you introduce the same security hole that gets does.

    EDIT

    D'oh. I'm an idiot. If you're trying to read a string containing spaces, you can't use the %s conversion specifier. Use the %[ conversion specifier instead:

    scanf( "%79[^\n]", mensage );
    

    That will read up to the next 79 characters or the newline, whichever comes first, and leaves the newline in the input stream.

提交回复
热议问题