UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

8.2.2.  The getchar function

The getchar function is equivalent to getc(stdin).

#include <stdio.h>
int getchar(void);

Here void indicates that no argument is needed for calling the function, because it will read in from the standard input.

The next program reads two characters typed in by the user from the keyboard, in the two different ways seen so far, and then displays the characters on the screen:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

int main(void)
{
  int ch1;
  char ch2;

  printf("Please, type in two characters together:\n");
  ch1 = getc(stdin);
  ch2 = getchar();
  printf("The first character you have typed is: %c\n",ch1);
  printf("The second character you have typed is: %c\n",ch2);
  return 0;
}

As you can see in the program listing, even though the functions expect an integer variable, the ch2 variable can be declared as a char. This is correct because, internally, what is stored of a variable of char type is its numeric value, so they can be passed to the functions that expect an int type.