C getchar() Function Tutorial

  • Post author:
  • Post category:C

In this section, we will learn what the getchar() function is and how to use it in C.

What is getchar() Function in C?

In the scanf-function section, we mentioned that in order to get a character from a user as the input to a program, we can use `%c` conversion-specifier.

But the C language provided another way of getting a character from a user and that is via the `getchar` function.

Note: the prototype of this function is in the `<stdio.h>` header file and so we need to include this header file if we used the function in a program.

C getchar() Function Syntax:

int getchar(void)

C getchar() Function Parameters:

As you can see, this function does not need any argument, and by calling the function, it’ll ask the user to enter a character.

C getchar() Function Return Value:

The return type of this function is an `int` and this is because characters behind the scene are treated as integer values. You can read more about this in the data-types section.

Example: using getchar() function in C

#include <stdio.h>

int main() {

    char c ;

    printf("Please enter a character: \n");
    c = getchar();

    printf("The character you typed is: %c",c);

    return 0;
}

Output:

Please enter a character:

k

The character you typed is: k

How does getchar() function work in C?

As mentioned in the scanf section, any value we enter to a program, it is first stored in the memory and then from there, functions like the `scanf` will check and read those data.

The `getchar` function does the same work. It reads data from the memory and if there’s no data in there, then in that case the program will ask the user to enter an input when the CPU reached the `getchar` function.

Example: C getchar() function

#include <stdio.h>

int main() {

    char c ;
    char scan;
    printf("Please enter something: \n");
    scanf("%c",&scan);

    c = getchar();

    printf("The first character you typed is: %c and the second character is: %c",scan,c);

    return 0;
}

Output:

Please enter something:

546tre

The first character you typed is: 5 and the second character is: 4

As you can see, we entered `546tre` as the input value of the program once and this data is stored in the memory.

After that, both the `scanf` and `getchar` functions took their data from the buffer in the memory where this data is stored.

Note that here the input value we’ve put into the program was `546tre` this means there are still 3 characters left in the memory and if we call the `getchar` function three times more, we will get these values from the memory as well.

Leave a Reply