954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with getchar()

Hi,

I've been having some problems with the getchar() statement. When I put it in a loop (to make an interactive input), I can't get user input anymore from within the loop.

Even the following simple program doesn't work:

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

int main(void)
{
    char response, text[255];
    int num;

    do
    {
        printf("Enter a number: ");
        fflush(stdout);

        fgets(text, 255, stdin);
        num = (int)strtol(text, NULL, 10);
        printf("You entered the number: %d\n", num);
        fflush(stdout);

        printf("\nRun again? ");
        fflush(stdout);
        response = getchar();
    } while (response != 'n');
    return EXIT_SUCCESS;
}


(On my computer, I had to place the fflush() statements, otherwise I wouldn't see the output).

The program above allows me to enter only ONE number. After that, it just says I entered 0.

What's going on and how can I solve this problem?

Dark_Knight
Newbie Poster
8 posts since Jan 2008
Reputation Points: 10
Solved Threads: 0
 

The problem that you're experiencing is that getchar() only grabs a single character from the input buffer. This would be fine, except that there's still a newline left in the input buffer that resulted from hitting 'enter' after your input. fgets() is next in your loop, and all it gets is the newline left behind, which is why you get a 0. You need to clear the input buffer after you use getchar() like this:

char c;
while ((c = getchar()) != '\n' && c != EOF);
John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You