The problem is that your newline gets buffered and passed onto the next getchar
call. You need to deal with the buffered newline in perhaps the following way:
printf("enter the firstkeyword \n");
scanf(" %c", &a);
printf("enter your second keyword \n");
scanf(" %c", &b);
The space before %c
is a common idiom that tells scanf
to ignore any space before the following character which in our case also includes the newline. It is not necessary in the first instance in this particular case but vital in the second.
You also don't need the stdlib
include and you can return
without the brackets, like return 0;
Actually, if you feel like experimenting and you are on a Linux terminal, you can set the terminal in raw mode which will remove any buffer and parsing abilities that the terminal would provide for you. To do that run /bin/stty raw
in the terminal.
This way there will be no buffering and you won't have to worry about any buffered newlines. The output on the console will look funny though (I've entered here a
and b
) unless you also regulate that with placing strategically carriage returns (\r
):
$ ./a.out
enter the firstkeyword
aenter your second keyword
bhere'b'is greater than 'a'
I've used your original code for the above.
To restore it, just run /bin/stty cooked