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?

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);
Member Avatar for thendrluca

after getchar i use another getchar to clear the buffer
char value = getchar();
char clear = getchar();
in value we will have what we want, but clear clears the \n
the solution above is for clearing all the buffer till and \n character

after getchar i use another getchar to clear the buffer

Though there's no guarantee that the second character is a newline, so you're making an unwarranted assumption about the user's behavior.

Member Avatar for thendrluca

i said that solution above is general :D

i said that solution above is general :D

And I implied that your solution is brittle. ;D

The reason you are getting 0 is that when you hit enter, it is taken by fgets() as an input which then goes to strtol() and it gives result as 0.

Add an extra getchar() after response = getchar();

 #include <stdio.h>
    #include <stdlib.h>
    int main(void)
    {
    char response, text[255];
    int num;
    do
    {

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

    printf("\nRun again? ");

    response = getchar();
    getchar();
    } while (response == 'y');
    return EXIT_SUCCESS;
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.