Explain character input/output and safe whole-line input in C.
5 marks
Answer in brief
Character input/output functions handle individual characters. Line input/output functions handle a string containing a line of text.
Character functions
getchar: Reads one character from standard input. Store its result in int so that the special end-of-input value EOF can be detected.
putchar: Writes one character to standard output. For example, putchar('A'); displays A.
Line functions
fgets: Reads at most one less than the supplied array size and adds a terminating null character when successful. It keeps the newline if it reads one.
puts: Writes a string and then adds a newline.
Header: Include stdio.h before using these functions.
Example
For char name[40];, fgets(name, sizeof name, stdin) reads a line into name if the call succeeds. It can store at most 39 input characters plus the terminating null character. If the line is longer, part of it remains unread. Check that the result is not NULL before using the line.
Important points
Check for EOF before treating a getchar result as a character. Do not use gets: it cannot limit the input size and has been removed from standard C. Functions such as getch from conio.h are not part of standard C. After numeric scanf input, a newline may remain; the next line read may read that newline. Plan the input sequence carefully.
Reference tables
↔ Scroll horizontally on a small screen
Character and line functions
Function
Purpose
Important detail
getchar()
Reads the next input character.
Returns int so it can represent an unsigned-char value or EOF.
putchar(ch)
Writes one character.
Use a character value, not a string pointer.
fgets(buffer, size, stdin)
Reads at most size − 1 characters.
On success, adds a null terminator; a read newline is retained.
puts(text)
Writes a string followed by a newline.
Do not add an unwanted second newline.
↔ Scroll horizontally on a small screen
Input requirements
Need
Suitable starting point
Extra responsibility
One next character
getchar
Handle EOF and any whitespace deliberately.
A bounded whole-line segment
fgets
Detect a missing newline if truncation matters.
A numeric token
Checked formatted input or checked text conversion