Reading a single character from stdin

Reading a single character from stdin#

int getchar(void);

Reads only a single character.

#include <stdio.h>

const char TEMPLATE[] = R"(
read character
as char: %1$c
as int: %1$d
)";

int main() {
  printf("Enter a character: ");
  auto input_char = getchar();
  printf(TEMPLATE, input_char);
}
$ echo geko | code-wi/reading_a_single_character.exe
Enter a character: 
read character
as char: g
as int: 103
🤔 Question to ponder

Why does our program not do something before we use Enter?

Activity 25 (Character counter)

Write a program that after each character input shows a counter of total number of space characters. It only reads one character and must discard others. e exits your program.

Use isspace(int ch) from ctype.h that outputs true if a character is a space character.

Enter a character: 3
Total: 0
Enter a character: 
Total: 1
Enter a character: leverpostej
Total: 1
Enter a character: e