Capture input from the Console
This document explains how to capture character and newline input from the console.
Retrieving Character Input from the User
It is possible to capture character input from the console using the scanf C library function.
For example, capture a character input using
scanf("%c", &input_char);
Detecting When the User Presses Return
Our UI console sends a new line (\n
) when you hit return but doesn't send a carriage return (\r
). When detecting a new line in code, use \n
rather than \r
.
For example the following will run, whereas using \r
will hang:
while ( getchar() != '\n');
Modify How the Terminal Handles "newline"
Alternatively, you can adjust the terminal settings to not map CR to NL using the command stty -icrnl
.
You can then send a \r
by pressing Ctrl+M or \n
by pressing Ctrl+J.