0

I was writing a code to check occurrence of a char in a string.After running the compiler took input for the string but it skipped the 2nd scanf just below the for loop. But when i wrote the scanf to get character above the loop both scanf were running. So i tried fflush(stdin) because i just know i little bit about buffer. Can someone explain in detail how is the compiler working with and without fflush(stdin).

PS : I could have used gets() I just want to know the concept.

int i, k=0;
char a[20], ch;

for(i=0; i<5; i++);
    scanf("%s", &a);

//fflush(stdin);
scanf("%c", &ch);      //This line is not working if i dont put fflush(stdin) or write it above loop 
DK_bhai
  • 337
  • 3
  • 14
  • Why are you calling `scanf` in a loop and overwriting the same buffer every time (without using it). It might be right but just looks strange so wanted to ask. Also, please update the question with the exact test log - that is, show what you entered. – kaylum Nov 30 '19 at 06:41
  • 1
    `scanf("%s", &a);` is a recipe for buffer overruns. Never write into an array with unspecific length, because longer input will write outside the buffer and corrupt your program. – John Zwinck Nov 30 '19 at 06:42
  • 1
    How are you accounting for the `'\n'` left in `stdin` by `scanf("%s", &a);` (as `"%s"` ignores leading whitespace), when you call `scanf("%c", &ch);` (which uses `"%c"` which does not ignore leading whitespace -- along with `"%[...]"`). Hint, you can cause `scanf` to ignore all leading whitespace by including whitespace in your format string, e.g. `scanf(" %c", &ch);` -- notice the `' '` (space)... – David C. Rankin Nov 30 '19 at 06:45
  • 2
    P.S. *No*, you could not have used `gets()`, see: [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used), but you could have used `fgets()`... – David C. Rankin Nov 30 '19 at 06:47
  • 2
    Any point to this line? `for(i=0; i<5; i++);` (note the semicolon at the end)? – John3136 Nov 30 '19 at 06:49
  • My bad there would be %c instead of %s typing error. – DK_bhai Dec 01 '19 at 04:39

0 Answers0