Difference between scanf() and fgets()

前端 未结 6 1242
灰色年华
灰色年华 2020-12-01 03:24

I want to know what is the difference between fgets() and scanf(). I am using C as my platform.

6条回答
  •  囚心锁ツ
    2020-12-01 04:05

    It should be noted that scanf pattern specs do allow field width limits:

    scanf( " %80s", mybuffer );
    

    But, where printf() allows the width to be passed as a variable (with '*'):

    printf( "My name is %*s.\n", 20, name );
    

    scanf() does not. (It interprets the '*' as a flag to suppress/ignore the field entirely.) Which means you end up doing things like this:

    #define NAMEWIDTH 40
    char buffer[ NAMEWIDTH + 4 ];
    ...
    scanf( " %40x", buffer );
    

    and no way to connect the field width 40 in the scanf() with the buffer width 40 in the buffer declaration.

提交回复
热议问题