Search code examples
cgetcharubuntu-17.10

can't use 2 getchar() function in a simple C snippet code


I'm kind of noob at programming and specially in C lang. I'm trying some code to learn more about C syntax.here's my question: why the second getchar() in the bellow snippet code doesn't work? I mean I want to console wait till I Enter and then finish.

#include<stdio.h>
#include<curses.h>

int main() {
    char ch = getchar(); 
    getchar();

    return 0;
}

PS: I use ubuntu 17.10.


Solution

  • As mentioned in the comments, you are typing two characters. Letter a and the new line character(\n). show second getchar() accept \n.

    If you want to use second getchar() then before using it use fflush(stdin). fflush(stdin) normally deletes (flushes) this type of extra character (in your case \n). or you can do as below

    #include<stdio.h>
    #include<curses.h>
    
    int main() {
        char ch;
        printf("Enter a charcter: ");
        ch = getchar(); 
        printf("\nyou typed the character ");
        putchar(ch);
        while ((getchar()) != '\n');     //fflush(stdin);   /* use this*/
        getchar();
    
        return 0;
    }
    

    Here “while ((getchar()) != ‘\n’);” reads the buffer characters till the end and discards them(including newline) and using it after the “scanf()” statement clears the input buffer and allows the input in the desired container.

    And also see the following links.

    1. Replacement of fflush(stdin)
    2. Alternative to C library-function fflush(stdin)
    3. Using fflush(stdin)
    4. Clearing The Input Buffer In C/C++