Character Input Output using getchar and putchar

In the previous tutorial, we learned how to use printf and scanf functions to get a character from the user and show it on the screen. Now, in this new tutorial, we will learn about two additional methods: getchar() and putchar(). These methods are specially made to get and show just one character at a time.


Basics of getchar and putchar

The getchar() function is used to get a character from the user. Unlike scanf(), which is used for inputting different types of data, getchar() specifically returns the character it reads. To store the returned character, we need to use a variable. The following lines of code demonstrates how to store the returned character in a variable named ch:

char ch;
ch = getchar();

Please note that getchar() always returns an integer value, not a character. So, in some programs, you may see the variable type as “int” instead of “char”. However, this is not an issue as long as you understand that internally, all characters are represented in binary and can be represented in decimal.

The putchar() function is used to display/print the character provided to it as an argument. For example, the following lines of code will print the character ‘d’ on the screen:

char ch = ‘d’;
putchar(ch);

It is recommended to use getchar() and putchar() instead of scanf() and printf() when working with characters in C, as these functions are specifically designed for handling character input and output.


Program to Count the Number of Characters in a Line

In the last tutorial, we learned how to count the number of characters using the while loop. At that time, we received characters from the user using the scanf() function. Let’s now replace the scanf() by getchar() to receive the characters. Here’s a program that counts the number of characters in a line using the getchar() function instead of scanf():

#include <stdio.h>
int main()
{
    int count = 0;
    char ch;
    ch = getchar();
    while(ch != '\n') {
        count = count + 1;
        ch = getchar();
    }
    printf("There are a total of %d characters in the line entered by you.", count);
    return 0;
}

Output:

In this program, we use getchar() to receive characters from the user until a newline character (‘\n’) is encountered. The count variable keeps track of the number of characters entered. Finally, we display the count using printf().

The program can be further simplified by including the getchar() function within the while loop:

#include <stdio.h>
int main()
{
    int count = 0;
    char ch;
    while((ch = getchar()) != '\n') {
        count = count + 1;
    }
    printf("There are a total of %d characters in the line entered by you.", count);
    return 0;
}

Output:

Explanation:
In this simplified version, we no longer need the initial getchar() function outside the while loop. Instead, we include the getchar() function within the parentheses of the while loop condition. The expression (ch = getchar()) receives a character from the user and assigns it to the variable ch. Then, it checks if ch is not equal to '\n'. If the condition is satisfied, the body of the loop will be executed, incrementing the count variable.

By including getchar() in the condition itself, we eliminate the need for the initial getchar() and the subsequent assignment within the loop.


Try it yourself

Question:

Do you remember that in the previous tutorial, I provided you with a program that got stuck in an infinite loop because the format string of the scanf function started with a space? Now, can you modify that program by using getchar() instead of scanf() to count the number of characters without considering whitespaces?

I have modified the program and I want to check my solution with yours.
I don’t how to do this, but I would love to see your explanation.
explanation

The following program will print the number of characters entered by the user without counting whitespaces:

#include <stdio.h>

int main()
{
    int count = 0;
    char ch;
    while((ch = getchar()) != '\n') {
        if (ch != ' ' && ch != '\t') {
            count = count + 1;
        }
    }
    printf("count = %d", count);
    return 0;
}

Output:

Explanation:
Inside the “if” statement, we check if the received character is neither a blank space (‘ ‘) nor a tab (‘\t’). If it is not a whitespace character, we continue with the loop and increment the count. The rest of the code is self-explanatory.

If you still prefer to use the scanf function to count the number of characters without considering whitespaces, you can use the following program:

#include <stdio.h>

int main()
{
    int count = 0;
    char ch;
  
    scanf("%c", &ch);
    while (ch != '\n') {
        if (ch != ' ' && ch != '\t') {
            count++;
        }
        scanf("%c", &ch);
    }
  
    printf("There are a total of %d characters in the line entered by you.", count);
    return 0;
}

Please note that the format specifier in the scanf function should not have a space at the beginning. Otherwise, the code will not function as intended.


Summary

In this tutorial, we learned about two new functions called getchar and putchar that can be used instead of scanf and printf. These functions are specifically designed to handle single characters.

The getchar function is used to receive a single character from the user. It returns an integer value that represents the character. On the other hand, the putchar function is used to display or print a character on the screen.

We also saw an example program that showed how to count the number of characters in a line entered by the user using getchar. We replaced the problematic scanf function that caused an infinite loop with getchar to fix the issue.



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.