【发布时间】:2013-08-21 04:40:58
【问题描述】:
当输入字符串超过其预定义的限制时,我在使用 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 接受的字符串大小,应该怎么做?
非常感谢
【问题讨论】:
-
如果您继续编辑您的帖子,其他人的答案在未来将没有任何意义。 SO 的目的不是解决具体问题,而是帮助他人寻找答案。
-
我会恢复它。对不起!
-
@IDK 请不要回复,现在问题似乎你需要什么......