4

当输入字符串超过其预定义的限制时,我遇到了 fgets 的一个小问题。

以下面的例子为例:

    for(index = 0; index < max; index++)
    {printf(" Enter the %d string : ",index+1)
                if(fgets(input,MAXLEN,stdin))
                {
                    printf(" The string and size of the string is %s and %d \n",input,strlen(input) + 1);
                    removeNewLine(input);
                    if(strcmp(input,"end") != 0)
                   { //Do something with input
                   }
                }

现在,当我超过长度 MAXLEN 并输入一个字符串时,我知道输入将在 MAXLEN -1 处附加一个“\0”,就是这样。当我尝试输入不要求输入的第二个字符串时,就会出现问题

Output :
Enter the first string : Aaaaaaaaaaaaaaaaaaaa //Exceeds limit
Enter the second string : Enter the third string : ....Waits input

所以,我想我应该像在 C 中那样以标准方式清除缓冲区。它等到我输入

return

两次,第一次被附加到字符串中,下一次,期待更多的输入和另一个返回。1. 有什么方法可以在不输入额外return的情况下清空buffer?2. 如何实现相同的错误处理?因为 fgets 返回值将是 Non-null 并且 strlen(input) 给了我 fgets 接受的字符串大小,应该怎么做?

非常感谢

4

2 回答 2

4

如果我理解正确,看起来你想避免两次输入,当输入的输入在范围内时。

解决方法是

for(index = 0; index < max; index++)
{
    printf(" Enter the %d th string :",index);
    // if (strlen(input) >=MAXLEN )

    if(fgets(input,MAXLEN,stdin))
    {

        removeNewLine(input);

        if(strcmp(input,"end") != 0)
        // Do something with input 
          ;
    }
    if (strlen(input) == MAXLEN-1 )
      while((ch = getchar())!='\n'  && ch != EOF  );

 }

有一个限制,当输入的字符正好是 MAXLEN-2 时,它会再次要求输入两次。

否则,您可以简单地input按字符输入形成您的使用字符。

于 2013-08-21T06:14:18.277 回答
3
while ((c=getchar()) != '\n' && c != EOF)
    ;

或者:

scanf("%*[^\n]%*c");
于 2013-08-21T04:44:28.587 回答