Return Values of getchar() in C
The getchar() function returns an integer value representing the character read from the standard input stream. However, it's important to understand the different return values & their meanings.
If the read operation is successful, getchar() returns the character read as an unsigned char cast to an int. This means that the returned value will be in the range of 0 to 255, inclusive.
If the end-of-file (EOF) condition is encountered, getchar() returns the special value EOF, which is typically defined as -1. The EOF condition indicates that there are no more characters to be read from the input stream.
It's crucial to check the return value of getchar() to handle different scenarios appropriately.
Let’s look at an example that shows checking the return value:
#include <stdio.h>
int main() {
int ch;
printf("Enter characters (press Ctrl+D to end): ");
while ((ch = getchar()) != EOF) {
printf("You entered: %c\n", ch);
}
printf("End of input.\n");
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter characters (press Ctrl+D to end):
h
You entered: h
e
You entered: e
l
You entered: l
l
You entered: l
o
You entered: o
You entered:
World
You entered: W
You entered: o
You entered: r
You entered: l
You entered: d
After the user presses Ctrl+D, the program will output:
End of input.
In this example, getchar() is called repeatedly in a while loop until the EOF condition is encountered. The loop continues to read characters from the user & print them back until the user presses Ctrl+D (on Unix-like systems) or Ctrl+Z (on Windows) to signal the end of input.
Examples of getchar() in C
Let's look at the examples to understand the use of getchar() in different scenarios.
Example 1: Reading & Printing Characters
#include <stdio.h>
int main() {
int ch;
printf("Enter characters (press Enter to end):\n");
while ((ch = getchar()) != '\n') {
printf("You entered: %c\n", ch);
}
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter characters (press Enter to end):
Coding
You entered: C
You entered: o
You entered: d
You entered: i
You entered: n
You entered: g
In this example, getchar() is used to read characters from the user until the user presses the Enter key (newline character). Each character is printed back to the user as it is entered.
Example 2: Counting Vowels
#include <stdio.h>
#include <ctype.h>
int main() {
int ch;
int vowelCount = 0;
printf("Enter a sentence (press Enter to end):\n");
while ((ch = getchar()) != '\n') {
ch = tolower(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}
printf("Number of vowels: %d\n", vowelCount);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter a selentence (press Enter to end):
CodingNinjas
Number of vows: 4
This example shows how getchar() can be used to read characters from a sentence entered by the user. It counts the number of vowels in the sentence by checking each character against the lowercase vowels. The tolower() function from the ctype.h library is used to convert each character to lowercase for case-insensitive comparison.
Example 3: Reading & Storing Characters in an Array
#include <stdio.h>
#define MAX_SIZE 100
int main() {
char str[MAX_SIZE];
int i = 0;
printf("Enter a string (press Enter to end):\n");
while (((str[i] = getchar()) != '\n') && i < MAX_SIZE - 1) {
i++;
}
str[i] = '\0'; // Null-terminate the string
printf("You entered: %s\n", str);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter a string (press Enter to end):
Beautiful
You entered: Beautiful
In this example, getchar() is used to read characters from the user & store them in a character array str. The loop continues to read characters until the user presses Enter or the maximum size of the array is reached. The null character ('\0') is appended to the end of the string to properly terminate it. Finally, the entered string is printed back to the user.
Example 4: Validating User Input
#include <stdio.h>
int main() {
char ch;
printf("Enter a character (Y/N): ");
ch = getchar();
// Clear the input buffer
while (getchar() != '\n') {
// Discard remaining characters
}
if (ch == 'Y' || ch == 'y') {
printf("You entered Yes.\n");
} else if (ch == 'N' || ch == 'n') {
printf("You entered No.\n");
} else {
printf("Invalid input. Please enter Y or N.\n");
}
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter a character (Y/N): Y
You entered Yes.
In this example, getchar() is used to read a single character from the user for input validation. The program expects the user to enter either 'Y' or 'N' (case-insensitive). After reading the character, a while loop is used to clear the input buffer by discarding any remaining characters until a newline character is encountered. This ensures that the next input operation starts fresh. Finally, the entered character is checked, & the appropriate message is printed based on the user's input.
Example 5: Encrypting & Decrypting Characters
#include <stdio.h>
#define ENCRYPTION_KEY 3
int main() {
char ch;
printf("Enter a message to encrypt:\n");
// Encryption
while ((ch = getchar()) != '\n') {
if (ch >= 'a' && ch <= 'z') {
ch = ((ch - 'a' + ENCRYPTION_KEY) % 26) + 'a';
} else if (ch >= 'A' && ch <= 'Z') {
ch = ((ch - 'A' + ENCRYPTION_KEY) % 26) + 'A';
}
putchar(ch);
}
printf("\nEnter the encrypted message to decrypt:\n");
// Decryption
while ((ch = getchar()) != '\n') {
if (ch >= 'a' && ch <= 'z') {
ch = ((ch - 'a' - ENCRYPTION_KEY + 26) % 26) + 'a';
} else if (ch >= 'A' && ch <= 'Z') {
ch = ((ch - 'A' - ENCRYPTION_KEY + 26) % 26) + 'A';
}
putchar(ch);
}
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter a message to encrypt:
I am fine
L dp ilqh
Enter the encrypted message to decrypt:
This example demonstrates a simple encryption & decryption program using getchar(). The program prompts the user to enter a message to encrypt. It then uses getchar() to read each character of the message. If the character is a lowercase or uppercase letter, it applies a basic encryption algorithm by shifting the character by a fixed number of positions (defined by ENCRYPTION_KEY) within the respective alphabet range. The encrypted character is then printed using putchar().
After the encryption, the program prompts the user to enter the encrypted message to decrypt. It again uses getchar() to read each character of the encrypted message & applies the reverse of the encryption algorithm to decrypt the characters. The decrypted characters are printed using putchar().
Read a Single Character Using the scanf() Function
While getchar() is a convenient way to read a single character from the standard input stream, you can also use the scanf() function to achieve the same result. The scanf() function is a more versatile input function that allows you to read formatted input, including single characters.
To read a single character using scanf(), you can use the %c format specifier.
For example :
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("You entered: %c\n", ch);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter a character: G
You entered: G
In this code snippet, scanf() is used with the %c format specifier to read a single character from the user. The & operator is used to pass the address of the ch variable to scanf(), allowing it to store the read character in the variable.
It's important to note that scanf() leaves the newline character in the input buffer after reading the character. If you want to consume the newline character, you can add a space before the %c format specifier, like this:
scanf(" %c", &ch);
The space before %c tells scanf() to skip any leading whitespace characters, including the newline character.
Let’s look at an example that shows reading multiple characters using scanf():
#include <stdio.h>
int main() {
char ch1, ch2, ch3;
printf("Enter three characters: ");
scanf(" %c %c %c", &ch1, &ch2, &ch3);
printf("You entered: %c, %c, %c\n", ch1, ch2, ch3);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter three characters: A X W
You entered: A, X, W
In this example, scanf() is used to read three characters from the user. The format specifier " %c %c %c" tells scanf() to read three characters separated by whitespace. The characters are stored in the variables ch1, ch2, and ch3, respectively.
Read the Characters Using a do-while Loop
When reading characters from the user, you may want to continue reading until a specific condition is met, such as reaching the end of a line or encountering a specific character. One way to achieve this is by using a do-while loop in combination with getchar().
For example :
#include <stdio.h>
int main() {
int ch;
int count = 0;
printf("Enter characters (press Enter to end):\n");
do {
ch = getchar();
if (ch != '\n') {
printf("Character %d: %c\n", ++count, ch);
}
} while (ch != '\n');
printf("Total characters entered: %d\n", count);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter characters (press Enter to end):
Hello
Character 1: H
Character 2: e
Character 3: l
Character 4: l
Character 5: o
Character 6:
Total characters entered: 6
In this example, a do-while loop is used to repeatedly call getchar() and read characters from the user until the newline character ('\n') is encountered, indicating the end of the line.
The loop starts by reading a character using getchar() and storing it in the ch variable. Inside the loop, the character is checked to ensure it is not a newline character. If it is not a newline character, the character is printed along with its count using printf(). The count variable is incremented using the prefix increment operator (++count) to keep track of the number of characters entered.
The loop continues to iterate as long as the character read is not a newline character. Once the newline character is encountered, the loop terminates, and the total count of characters entered is printed.
Let’s look at an another example that shows reading characters until a specific character is encountered:
#include <stdio.h>
int main() {
int ch;
printf("Enter characters (press 'q' to quit):\n");
do {
ch = getchar();
if (ch != 'q' && ch != '\n') {
printf("You entered: %c\n", ch);
}
} while (ch != 'q');
printf("Program terminated.\n");
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Enter characters (press 'q' to quit):
Hello q
You entered: H
You entered: e
You entered: l
You entered: l
You entered: o
You entered:
Program terminated.
In this example, the do-while loop continues to read characters using getchar() until the character 'q' is entered by the user. Inside the loop, the character is checked to ensure it is not 'q' and not a newline character. If the condition is satisfied, the character is printed using printf().
The loop keeps iterating as long as the character read is not 'q'. Once the character 'q' is encountered, the loop terminates, and a message indicating the program's termination is printed.
Frequently Asked Questions
What happens if I don't check the return value of getchar()?
If you don't check the return value of getchar(), you won't be able to detect the end-of-file (EOF) condition or handle input errors effectively. It's important to check the return value to ensure proper program behavior.
Can I use getchar() to read numeric input?
While getchar() is primarily used to read character input, you can still use it to read numeric input by reading each character individually and then converting the characters to their corresponding numeric values using functions like atoi() or strtol().
Is there any limitation on the number of characters I can read using getchar()?
There is no inherent limitation on the number of characters you can read using getchar(). You can keep reading characters until you encounter the end-of-file (EOF) condition or until a specific condition is met based on your program's logic.
Conclusion
In this article, we explained the concept of the getchar() function in C, which allows you to read a single character from the standard input stream. We covered the syntax of getchar(), its return values, and different code examples to understand its use. We also discussed alternative ways to read characters, like using scanf() and using a do-while loop for continuous reading until a specific condition is met.
You can also check out our other blogs on Code360.