0

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.

  • 5
    You typed two characters, a letter (say) such as `a` and a return (newline, `\n`). The second `getchar()` reads the newline. – Jonathan Leffler Mar 01 '18 at 08:31
  • Also, unless you actually plan on using `curses.h` functions, you should remove the header. Currently your code makes use of the `stdio.h` functions only (which is as it should). Since you are using Ubuntu, get used to using the `man` pages (e.g. `man printf` or `man getchar`). They show exactly what header is required for each function. – David C. Rankin Mar 01 '18 at 08:37
  • since I don't undrestand what you mean( cuz I have 1 character in the snippet code andand I don't know which func return newl ine!!) I shorten the code. now can you explain me ? again NOOB! – oldMCdonald Mar 01 '18 at 10:26

1 Answers1

1

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++
yajiv
  • 2,726
  • 1
  • 12
  • 22