fgets阻塞 stdin 退出_如何清除后与fgets溢出输入缓冲区?

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

Taking the example below:

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

}

}

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

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

return

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?

Thanks a lot

解决方案

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

A work around would be

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 );

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值