topskill.dev
CoursesTracks
All courses/C Programming for BeginnersInput and Diagnostics in a Local Terminal
Input and Output Safely
9 / 10
← C Programming for Beginners
○What a program actually does○The computer and the operating system○From a C file to a running program○Compiled and interpreted programs○Trace One Tiny C Program○Print the Opening Sign✦Module Quiz
○Your First C Program○Variables and Formatted Output○Arithmetic and Integer Division○Formatting and Numeric Conversion○Calculate a Shop Total✦Module Quiz
○Declare and initialize variables○Label the parts bin○Assign a new value○Update the checkout board○Choose int, double, and char○Write a battery test label○Keep local names and constants clear○Count free kit slots✦Module Quiz
○Match printf placeholders and arguments○Print a radio test slip○Build lines with escapes and multiple calls○Print a clock pickup note○Print percent signs and aligned values○Line up a cleaning report○Evaluate expressions before printing○Divide reflectors among trays✦Module Quiz
○Comparisons and True or False○How if and else Choose a Path○Choose a Ticket Message○Select a Fixed Choice with switch○Choose a Service Desk✦Module Quiz
○For Loops: Repeat a Known Number of Times○Add Daily Contributions○While Loops: Repeat While a Condition Holds○Make a Countdown○Run Once with do while○Label a Two-Row Shelf○Label Tool Drawers✦Module Quiz
○Define and Call a Function○Follow a Function Call and Its Return Value○Return a Square○Declare Before a Function Call○Declare and Convert✦Module Quiz
○Arrays and Zero-Based Indexes○Add Array Elements○Count Array Slots Safely○Average Workshop Ratings○Rows and Columns in Memory○Total a Two-Row Grid✦Module Quiz
○C Strings and the Null Terminator○Count a Label○Compare Complete Strings○Verify a Pickup Code○Visit Each Character○Count a Letter in a Label✦Module Quiz
○Pointers: Addresses and Dereferencing○Update Through a Pointer○Pass an Address to a Function○Swap Two Counts○Array Addresses and Offsets○Total with an In-Bounds Pointer○Null, Validity, and Lifetime○Handle an Optional Pointer✦Module Quiz
○Pass an Array and Its Length○Total Readings in a Function○Change Array Elements Through a Parameter○Update Each Stock Count✦Module Quiz
○Define a Supply Record○Record Thread Supplies○Update a Record Member○Update the Paper Stock○Walk an Array of Records○Total the Flyer Stacks○Pass a Record to a Function○Print a Badge Record✦Module Quiz
○One Value in Shared Storage○Record One Ticket Value○A Tag Tells You What Is Stored○Read a Tagged Repair Ticket○Compare Union and Struct Storage○Choose the Right Storage✦Module Quiz
○Read Bits with AND○Check an Equipment Flag○Turn a Flag On with OR○Mark a Kit Ready○Toggle and Clear Individual Flags○Toggle a Warning Flag○Move a Bit into Position○Build a Position Mask✦Module Quiz
○Include the Right Header○Measure a Label with strlen○Guard a Macro Default○Set a Fallback Badge Limit○Include Code Only for Debug Builds○Show an Inventory Diagnostic When Enabled○Parenthesize a Simple Macro○Keep a Macro Calculation Grouped✦Module Quiz
○Name a Status with enum○Confirm an Application Status○Alias a Record Type with typedef○Initialize a Ribbon Record✦Module Quiz
○Where the storage comes from○Request and Release an Array○Store Three Repair Counts○Start Allocated Counters at Zero○Start Station Counters at Zero○Allocate and Release Records○Allocate the parts report✦Module Quiz
○Print a Formatted Label○Print the carving sign○Print Characters with putchar○Build a two-letter mark○Format into a Bounded Buffer○Prepare the shelf label○Write a Line to stdout with fputs○Post the ready notice●Input and Diagnostics in a Local Terminal✦Module Quiz
Input and Output Safely

Input and Diagnostics in a Local Terminal

Read a line in a local terminal

The earlier lessons used values already in the program. Reading from the keyboard adds a new source of failure: input may end, be too long, or have the wrong form.

StreamPurpose
stdinInput, often the keyboard in a local terminal
stdoutOrdinary results and prompts
stderrDiagnostics, such as a failed input request

A terminal may display stdout and stderr together, but they remain separate streams. None of these names promises access to persistent operating-system files.

Optional local practice

The course's browser Run control does not provide an interactive keyboard prompt. Do not paste an input-waiting program into a graded exercise. The examples below are for a C compiler and terminal on your own computer, not browser Run blocks.

Save this program as main.c. In that directory, compile with cc -std=c11 -Wall -Wextra -Wpedantic -Werror main.c -o main, then run ./main. Type a short name and press Enter.

c
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[32];
    fputs("Name: ", stdout);
    fflush(stdout);
    if (fgets(name, sizeof name, stdin) == NULL) {
        fputs("No name read\n", stderr);
        return 1;
    }
    if (strchr(name, '\n') == NULL) {
        fputs("Use a shorter name and press Enter\n", stderr);
        return 1;
    }
    printf("Registered: %s", name);
    return 0;
}

fflush(stdout) asks the stream to deliver the prompt before the input call; the prompt has no newline. On success, fgets reads at most 31 characters into this 32-byte array, stops after a newline if it reaches one, and adds the null terminator. A NULL return means no usable input string was obtained, so that branch must not print name.

strchr, declared in <string.h>, searches a string for a character and returns its address, or NULL if it is absent. Here it checks whether the line's newline reached the buffer. We reject input without that newline and end the program rather than accidentally accept the first part of a long name. This also rejects a final unterminated line at end of input. A program that asked again would first need to deal with unread characters left in stdin.

For input Mira followed by Enter, the terminal shows the prompt and then Registered: Mira. fgets kept the newline, so the final printf does not add another. Never use gets: it cannot enforce the buffer's capacity and is not part of C11.

Reading one character

getchar() returns an int, not a char. The result must represent a character value or the special result EOF, which signals end of input or a read error. Test that result before treating it as a character:

c
#include <stdio.h>

int main(void) {
    int ch = getchar();
    if (ch == EOF) {
        fputs("No character read\n", stderr);
        return 1;
    }
    putchar(ch);
    putchar('\n');
    return 0;
}

Compile this as a separate program. Enter A and press Enter; it prints A. It consumes only the first character, not the rest of the line. Do not store getchar() directly in a char and then test for EOF: the conversion can lose the distinction.

You may also encounter scanf. It returns the number of input items successfully assigned, so one requested conversion needs a return value of 1 before you use its destination. A %d input conversion needs the address of an int, unlike %d output, which needs the value. A failed conversion can leave input unread; numeric input outside the destination type's range is another reason not to treat a return-value check as a complete validation strategy. For this course, use the bounded line example above and keep parsing user-entered numbers as a later topic.

The browser exercises remain independent of stdin and stderr capture. Finish the section quiz using the lifetime, formatting, and stream distinctions you have just practiced.