c - String length Error -


i reading string stdin using fgets function , trying print length of string, getting length of string 1 first time here code

#incldue<stdio.h> #include<string.h> int main(void) {    printf("\n enter no of test cases");    scanf("%d",&t);    int i,j;    for(i=0;i<t;++i)    {      char song[500],val[28];      int k=0,x=0;      fgets(song,500,stdin);      int len=strlen(song);      printf("\nlen=%d",len);    }   return 0; } 

i getting 1 length first test case :/ please suggest going wrong

you not clearing input buffer. after giving input value first scanf newline there. fgets not input user. newline placed in buffer in first(song[0]) position. reason strlen returns value 1.

make line before fgets.

int c; if ( == 0 )     while((c=getchar()) != '\n' && c != eof ); fgets(song,500,stdin); 

or else place line after getting input scanf.

scanf("%d",&t); while((c=getchar()) != '\n' && c != eof ); 

Comments

Popular posts from this blog

How to run C# code using mono without Xamarin in Android? -

python - Specify path of savefig with pylab or matplotlib -

c# - SharpSsh Command Execution -