如何清除后与fgets溢出输入缓冲区? [英] How to clear input buffer after fgets overflow?

查看:912
本文介绍了如何清除后与fgets溢出输入缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当输入字符串超过了predefined限制我面临着与fgets一个小问题。

I'm facing a little problem with fgets when the input string exceeds its predefined limit.

考虑下面的例子:

    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追加一个'\\ 0'-1,这将是它。在问题发生时,我尝试进入未要求即第二个字符串

Now when I exceed the length MAXLEN and enter a string, I know that the input will append a '\0' at MAXLEN -1 and that would be it. The problem happens when I try to enter the 2nd string which is not asked for i.e

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

所以,我想我应该清除缓冲区的标准方式为C.它等待,直到我进入

So, I thought I should clear the buffer the standard way as in C. It waits until I enter

return

两次,第一次被附加到字符串,下一次,期待着与另一回报更多的投入。
1.是否存在被我可以清除缓冲区,而无需输入超额收益的任何方法?
2.如何实现错误处理的一样吗?由于与fgets返回值将非NULL和strlen的(输入)让我通过与fgets字符串的被接受的大小,应该怎样做?

two times, The first time it being appended to the string and the next time,expecting more input with another return. 1. Is there any method by which I can clear the buffer without entering the extra return? 2. How do I implement error handling for the same? Because the fgets return value will be Non-null and strlen(input) gives me the accepted size of the string by fgets, what should be done?

非常感谢

推荐答案

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

If I understood correctly, looks like you want to avoid twice enter press, when entered input is within range.

一个变通是

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。

With a limitation that it will again ask for two times enter when entered characters are exactly MAXLEN-2.

否则你可以简单地使用逐个字符输入表格你的输入

Or else you can simply form your input using character by character input.

这篇关于如何清除后与fgets溢出输入缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆