2017-03-23 107 views
0

在這個論壇上關於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\不起作用的答案。

我敢肯定,我俯瞰在令人眼花繚亂的明顯,但如果有人可以把我從我的痛苦,我會非常感激。

非常感謝

彼得

回答

0

您可能要添加一個調用

fflush(stdin); 

在您致電fgets之前或之後,清除緩衝區中的任何多餘字符。