getchar() reads the next byte from standard input and returns it as an int. Using int is important because the function must also be able to return the special value EOF.
int ch = getchar();
#include <stdio.h>
int main(void) {
int ch;
printf("Enter one character: ");
ch = getchar();
if (ch == EOF) {
printf("No input available.\n");
return 1;
}
printf("You entered: %c\n", ch);
return 0;
}
#include <stdio.h>
int main(void) {
int answer;
printf("Do you like C programming? Press Y or N: ");
answer = getchar();
if (answer == 'Y' || answer == 'y') {
printf("Keep practicing C.\n");
} else if (answer == 'N' || answer == 'n') {
printf("Try smaller examples and practice regularly.\n");
} else {
printf("Please enter Y or N.\n");
}
return 0;
}
Key change: keep reading until the newline character or end-of-file is reached.
#include <stdio.h>
int main(void) {
int ch;
printf("Enter text: ");
while ((ch = getchar()) != '\n' && ch != EOF) {
printf("Read: %c\n", ch);
}
return 0;
}
#include <stdio.h>
int main(void) {
int ch;
while ((ch = getchar()) != EOF) {
putchar(ch);
}
return 0;
}
This classic loop demonstrates why the return value should be stored in an int: a char may not be able to represent every byte value and EOF distinctly.
#include <stdio.h>
int main(void) {
int ch;
printf("Enter characters (q to quit):\n");
while ((ch = getchar()) != EOF && ch != 'q') {
printf("You entered: %c\n", ch);
}
return 0;
}
#include <stdio.h>
int main(void) {
printf("Press Enter to continue...\n");
(void)getchar();
printf("Program continued.\n");
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| nurr | 10-11-2013 |
| hi, how i'm going to change this code using string, for example Y change it to YES, and N change it to NO. thanks for help... | |
| Michael Ziile | 22-01-2019 |
| illustrate with examples a)reading character and string variable b)writing character and string variable | |