Ignoring all input characters until 'a' is entered - using scanf in C

Viewed 470

I am trying a basic code snippet on C. My intention is to ignore all characters until 'a' is entered by the user and then copy the next non-whitespace character to x.

#include <stdio.h>

int main()
{
    char x ;
    printf ("Input character - ") ;
    scanf  (" a %c", &x) ;
    printf ("x=%c is the input", x) ;
    return 0 ;
}

I give input in the console as:

a <enter>
s <enter>

I get the output as: x=s is the input. This is correct.

But when I give input in the console as:

b <enter>

The execution finishes suddenly and I get the output as: x= is the input.

I don't understand this behavior. I was expecting the program to ignore 'b' and subsequent characters until 'a' is entered by the user. Did I interpret the scanf statement wrongly?

2 Answers

Did I interpret the scanf statement wrongly?

Yes. Let's say scanf generally does:

  • reads one character from input
  • checks if it matches the format string
  • if it matches, scanf continues to the next part of the string
  • if it does not match, scanf calls ungetc and exits
  • scanf returns number of arguments scanned or EOF in case of error or if there were no arguments scanned.

If you do scanf(" a %c", &x);, and type b <enter> then:

  • scanf reads b
  • b does not match " " (space)
    • " " space is magical, it matches zero or more whitespace characters
    • so scanf continues
    • b does not match a
  • scanf calls ungetc('b')
  • scanf returns with EOF

In such case x is never assigned and x is uninitialized and contains some garbage value. Most probably in the output x=>here< is there is some unprintable invisible character.

By using scanf("a%c",&x); you are preformatting the input to be accepted if it would be like 'ab' , 'ac' , 'aa' and give 'b' , 'c' and 'a' as the o/p respectively, and will not accept anything alike those ones. (Can also give o/pfor inputs like 'aaa' , 'abc' as 'a' , 'b' respectively)

And for your task you can try this code below :- (Completely tested)

#include <stdio.h>

int main()
{
    char x ;
    do{
        scanf("%c",&x);
    }while(x != 'a');      //Read until x is not 'a'
    
    scanf("%c",&x);        //Read next character from standard input into x
    printf("%c",x);        //And then print x
    return 0 ;
}
Related