fgets()边界情况阻止等待输入

时间:2017-03-23 18:00:56

标签: fgets

关于这个论坛上的fgets()有很多问题,但是没有一个问题能为我提供这个问题的答案。

我一直在研究一些非常古老的C技能,并且一直在关注cprogramming.com上的教程。

我遇到第9课(http://www.cprogramming.com/tutorial/c/lesson9.html)的string.h示例问题:

#include <stdio.h>    /* stdin, printf, and fgets */
#include <string.h>   /* for all the new-fangled string functions */

/* this function is designed to remove the newline from the end of a string
entered using fgets.  Note that since we make this into its own function,
we could easily choose a better technique for removing the newline.  Aren't
functions great? */
void strip_newline( char *str, int size )
{
    int i;

    /* remove the null terminator */
    for (  i = 0; i < size; ++i )
    {
        if ( str[i] == '\n' )
        {
            str[i] = '\0';

            /* we're done, so just exit the function by returning */
            return;   
        }
    }
    /* if we get all the way to here, there must not have been a newline! */
}

int main()
{
    char name[50];
    char lastname[50];
    char fullname[100]; /* Big enough to hold both name and lastname */

    printf( "Please enter your name: " );
    fgets( name, 50, stdin );

    /* see definition above */
    strip_newline( name, 50 );

    /* strcmp returns zero when the two strings are equal */
    if ( strcmp ( name, "Alex" ) == 0 ) 
    {
        printf( "That's my name too.\n" );
    }
    else                                     
    {
        printf( "That's not my name.\n" );
    }
    // Find the length of your name
    printf( "Your name is %d letters long", strlen ( name ) );
    printf( "Enter your last name: " );
    fgets( lastname, 50, stdin );
    strip_newline( lastname, 50 );
    fullname[0] = '\0';            
    /* strcat will look for the \0 and add the second string starting at
       that location */
    strcat( fullname, name );     /* Copy name into full name */
    strcat( fullname, " " );      /* Separate the names by a space */
    strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */
    printf( "Your full name is %s\n",fullname );

    getchar();

    return 0;
}

这一切都适用于正常情况,但如果fgets()的输入长度为49个字符 - 应该允许,据我所知,假设缓冲区有50个插槽 - 第二次调用fgets()不要等待输入。

我见过的其他答案在调用fgets()之前讨论清除缓冲区,但即使设置缓冲区的第一个字符(lastname[0] = '\0\也不起作用。

我敢肯定我忽略了那个令人眼花缭乱的明显,但如果有人能让我摆脱困境,我会非常感激。

非常感谢

彼得

1 个答案:

答案 0 :(得分:0)

您可能想要添加对

的调用
 fflush(stdin);

在调用fgets之前或之后,从缓冲区中清除任何多余的字符。