OldSchool
OldSchool

Reputation: 2183

Behavior of scanf()

why the program is not stopping at the line 4 for taking the input?

int main(int argc, char *argv[])
{
  int a, b;
  char c1, c2;
  printf("Enter something: ");
  scanf("%d",&a); // line 1
  printf("Enter other something: ");
  scanf("%d", &b); // line 2

  printf("Enter a char: "); 
  scanf("%d",&c1); // line 3
  printf("Enter other char: ");
  scanf("%d", &c2); // line 4

  printf("Done"); // line 5

  system("PAUSE");  

  return 0;
}

i read this question from a book and in above line 4 the scanf() is not executing but why?

Upvotes: 1

Views: 442

Answers (3)

alexdotcom
alexdotcom

Reputation: 61

 printf("Enter a char: "); 
  scanf("%c",&c1); // line 3
  printf("Enter other char: ");
  scanf("%c", &c2); // line 4

change %d with %c (from decimal to character)

Upvotes: 0

Costis Aivalis
Costis Aivalis

Reputation: 13728

scanf has issues with the newline. A quick and dirty way to solve this, is by adding a space or a \n before %c in order to bypass that...

  printf("Enter a char: "); 
  scanf(" %c",&c1); // line 3
  printf("Enter other char: ");
  scanf(" %c", &c2); // line 4

Upvotes: 2

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

%d expects to read a bunch of digits from input, so that it can form an integer and store the result into the pointer you pass (which is invalid in this example, since you provided a pointer to char, but anyway, this is irrelevant here).

The problem is that if you input a character, scanf() will notice that there isn't a valid digit on input. It will read this character, push it back into the input, and return prematurely. This happens on line 3. Since the character was pushed back, line 4 will again retrieve the same character from input and see that there is no valid integer on input, so the same character is pushed back again.

The key point to keep in mind here is that scanf returns prematurely with invalid input, leaving the input stream untouched.

For example, if stdin holds the character a, scanf() on line 3 will retrieve an a from input. It sees that this cannot be a valid digit, so a "goes back" to stdin and scanf() returns. On line 4, the scanf call will do the same thing: it picks the next item from input, which is the same a, and returns prematurely. Scanning for integers won't work until you consume this character. For example, if you call getchar() after line 3, you consumed the problematic character, and scanf() on line 4 will wait for input.

Upvotes: 2

Related Questions