代码的问题 [英] Problem in the fgets of code

查看:84
本文介绍了代码的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <stdlib.h>

void fun(int choice);
int array[10];

void main()
{
   int choice,i;
   scanf("%d",&choice);
   for(i=0;i<choice;i++)
   {
       fun(i);

   }

for(i=0;i<choice;i++)
    printf("\n%d\n",array[i]);
}

void fun(int choice)
{
      char string[50];
      int k,count1=0,count2=0,j=0,temp=0;
     fgets(string,50,stdin);
     j=strlen(string);


    for(k=0;k<j;k++)
    {
        if(string[k]=='a')
        count1++;
    else if(string[k]=='b')
        count2++;
    else

    break;
    }

     temp=count1-count2;
     if(temp<0)
        array[choice]=count1;
     else if(temp>0)
        array[choice]=count2;
     else
       array[choice]=0;

}





我的尝试:



i需要输入测试用例选择= 3

循环似乎要去3次



虽然功能乐趣中的fgets只占用2个输入。取一个空字符作为第一个输入。为什么?如何纠正它



What I have tried:

i need to enter the test case choice=3
the loop seems to go 3 times

while the fgets in function fun is taking only 2 inputs .it take a null character as a first input .why ?how to correct it

推荐答案

参见为什么我们使用函数fflush(stdin)和fflush (stdout)在c? - Quora [ ^ ]。


也许看看这个 [ ^ ]关于主题的主题。
Maybe take a look at this[^] thread on the subject.


这篇关于代码的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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