Menu

Investigating getchar() function

Polina U
2008-07-27
2012-09-26
  • Polina U

    Polina U - 2008-07-27

    Windows XP
    DEV-C++ version 4.9.9.2
    programming in C


    Hi, I'm trying to investigate getchar() function behaviour using this simple program:

    include <stdio.h>

    include <stdlib.h>

    int main()
    {
    printf("press any key\n");
    char ch=getchar();
    printf("hallo\n");
    printf("%c", ch);
    system("PAUSE");
    return 0;
    }


    I expect it to print "press any key",wait for ANY input and then print "hallo". What actually happens is that only after pressing "ENTER" "hallo" is typed. Although I see that ch equals the first character that I enter. What is the program waiting for after accepting the value for ch?
    Thank you.

     
    • cpns

      cpns - 2008-07-27

      By default the console 'device' is used for standard input (stdin), the device itself is 'line buffered', so it presents nothing to the standard input functions until an entire line is entered. At that time there will be at least one characters in the buffer - '\n' caused by pressing ENTER preceeded by anything else you may have typed.

      To achieve the behaviour you want you will need platform specific I/O routines. In Windows these are provided by: http://msdn.microsoft.com/en-us/library/ms682073.aspx

      Or more simply you could use http://msdn.microsoft.com/en-us/library/aa297934(VS.60).aspx, however Dev-C++ is not provided with a Microsoft <conio.h>, and those that are available are are generally clones of the Borland conio routines which are very different. This is easily solved by adding your own prototype:

      extern int _getch( void );

      to your code.

      Clifford

       
    • Polina U

      Polina U - 2008-07-27

      Thanks, it works now :)

       
    • cpns

      cpns - 2008-07-27

      Sorry. This dumb forum included the ',' in the link text try: http://msdn.microsoft.com/en-us/library/aa297934(VS.60).aspx

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.