0 0 0 0


#include <stdio.h>
#include <stdlib.h>
int main()
    char a,b;
    printf("enter the firstkeyword n");
    a = getchar();
    printf("enter your second keyword n");
    b = getchar();
    printf("it is '%c' greater than '%c' as i expected n",a,b);
    else if (b>a)
    printf("here'%c'is greater than '%c' n",b,a);
    printf("dont type the same character twice in next session n");

after compiling the program the o/p is:

enter the first keyword

I entered '$' and used ctrl+z to eof and 'enter' to continue the program. But even without entering the second keyword the compiler printing the output as

enter your second keyword

it is '$' greater than '->' as i expected

Can anyone help with this program?

Sorry if any grammatical or phrase errors.

Best Answer:

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

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs