2012-12-11 119 views
-2

我一直在扯出我的头发,试图找出为什么它不会打印出测试消息并输入while循环。有任何想法吗?为什么不能进入while循环?

void getInput(char * string) 
{ 
    char * tempString; 
    int maxLength = 1026; // Accounts for NULL and \n. 
    tempString = malloc(maxLength * sizeof(char)); 

    fgets(tempString, maxLength, stdin); 
    size_t len = strlen(tempString); 


    while ((int)len > maxLength) 
    { 
    printf("Test"); 
    if (tempString[len-1] == '\n') 
    { 
     tempString[len-1] = '\0'; 
     len = strlen(tempString); 
    } // if 
    } // while 
+7

因为len不大于maxLength。 –

回答

6

fgets(tempString, maxLength, stdin);读取最多maxLength-1字节。有关详细信息,请参阅fgets man page

这意味着​​必须总是小于maxLength

您的意思是使用<作为您的循环测试吗?

while ((int)len < maxLength) 
+2

或者'while((int)len> 0)'。注意'len'永远不会在循环内增长。 –

+0

我想将len与MaxLength比较,如果它大于maxLength,则删除多余的字符,这是while循环的作用。 – AkshaiShah

+1

@AkshaiShah问题是,这里不能有任何多余的字符。如果有 - b!缓冲区溢出。 –

1

因为没有人做过,所以让我介绍一下手册页。如果您没有基于Linux的操作系统,只需在Google中键入man和函数名称即可,并且您将获得关于函数如何工作的说明。

Here's a man page for fgets()

字符*与fgets(字符* S,INT尺寸,FILE *流);
fgets()在中最多读入一个小于的字符,并将它们存储到s指向的缓冲区中。

因此,在你的代码:

fgets(tempString, maxLength, stdin); // size is maxLength 

你永远不会了解更多然后maxLength-1,这是功能是如何工作的。