1
votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{

       char p,q;
       printf("Hello enter char: ");
       p=getchar();
       printf("the char is: %c\n",p);

       printf("Hello enter char: ");
       q=getchar();
       printf("the char is: %c\n",q);
    return 0;
}

(WHY IS MY OUTPUT for the second printf and scanf not waiting for me to input a char before exiting the program?.....what i mean is u know where it says q=getchar();??? shouldnt it wait for to input a char before exiting the program? but for some reason the program just exits when it goes to the next line...

3
To what scanf() are you referring to? And when you "entered" your character and pressed the <enter> key on your keyboard, how many characters do you think you entered? Hint: it isn't one.WhozCraig
i see the first print out on the screen, then i type in one char, then press enter...then the computer prints out the second AND third print out....why isnt it just printing out the second printout and wait until i press enter after typing a char?Fuad Hossain
@HardyFeng oh thankyou!!! thats the problem...so please tell me how to fix this??Fuad Hossain
Enter key is also taken as input.Hardy Feng
And getchar() returns an int, not a char, despite the name.Crowman

3 Answers

1
votes

when pressing enter,a character '\n' is inputing.So your getchar() was used before you enter the second character.I think you want the code below:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char p,q;
    printf("Hello enter char: ");
    p=getchar();
    printf("the char is: %c\n",p);

    int c; 
    while((c = getchar()) != '\n' && c != EOF && c != ' ') ; 

    printf("Hello enter char: ");
    q=getchar();
    printf("the char is: %c\n",q);
    return 0;
}
0
votes

You can also use a getch() instead of getchar() to avoid pressing enter key.

#include <stdio.h>
#include <conio.h>

int main(void) 
{

       char p,q;
       printf("Hello enter char: ");
       p=getch();
       printf("the char is: %c\n",p);

       printf("Hello enter char: ");
       q=getch();
       printf("the char is: %c\n",q);
       return 0;
}
0
votes

When encountering invalid user inputs, use getchar() to read char, and other similar instances where there are undesired characters stuck at input stream(like in your case it was a newline) I define a constant named FLUSH

   #define FLUSH while(getchar() != '\n')

to solve the problem. What this statement does is that it reads a character and then throws it away. Now if you try to place it after one of your getchars i.e.

   p=getchar();
   printf("the char is: %c\n",p);
   FLUSH;

it will read the newline then stops because the condition within the while statement no longer holds.

Note: Using getchar() for prompts leaves a '\n' in the input stream you will find this troublesome once you make another prompt and have not eradicated that '\n'.