0

I have a code and I'm wondering what the difference between scanf() and to initialize an integer directly is. When I compile this code :

for(u=0;u<reihen;u++){                          
   fgets(a,MAX,stdin);
   k = strlen(a)-1;
   printf("Value of k: %d\n",k);
   for(z=0;z<k;z++){
   }
}
printf("hello");
}

with this initialization of "reihen"

scanf("%d",&reihen);

the code skips the fgets(a,MAX,stdin); and the rest of the code except for k = strlen(a)-1; and printf("Value of k: %d\n",k); but just for the first circuit. Then the code works fine.

and when I'm initialize the reihen directly like reihen = 2; It doesn't skip anything.

Could someone explain me this please ?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Clock_9
  • 143
  • 1
  • 1
  • 4
  • 2
    (not just a newline - `scanf` stops at *any* whitespace) – Jongware May 15 '15 at 15:33
  • and why does fgets() reads this Newline ? @user3121023 – Clock_9 May 15 '15 at 15:35
  • So scanf()'s buffer is "6\n" after getting input of 6 am i right ? And if this is right, why does fgets() gets this newline ? Its still in the buffer of scanf() isnt it ? @user3121023 – Clock_9 May 15 '15 at 15:45
  • 1
    @user3121023, you should formulate an answer based on the comments. Together, they answer the OP's question very well. – R Sahu May 15 '15 at 15:51

0 Answers0