C Standard I/O Functions

C Standard I/O Functions connect values in a program with readable text. You use them when a command-line utility reads measurements, displays a result, or reports an error. The central skill is matching each requested conversion to the correct argument, then checking whether the operation succeeded. This lesson focuses on formatted input and output rather than file positioning or storage formats.

Choose the function and header

The stdio.h header declares printf, scanf, fprintf, and related input/output functions. Include it before calling these functions. The stdlib.h header declares general utilities such as strtol and exit; including it does not replace the declaration of printf or scanf.


printf writes formatted text to standard output. scanf reads formatted input from standard input. Their fprintf and fscanf counterparts take an explicit destination or source as an additional argument. For example, fprintf(stderr, "Invalid reading\n"); sends a diagnostic to the standard error destination.


A format string is text that describes the literal characters and conversions an I/O function should process. In printf("Count: %d\n", count);, the label is literal text, %d requests an integer conversion, and \n represents one newline character.

Match conversions to argument types

A conversion specification is a format-string instruction beginning with % that controls how a value is written or read. Identical-looking specifications can have different argument requirements for output and input.


Specification

Argument for printf

Destination for scanf

%d

An int value

An address of an int

%f

A double value

An address of a float

%lf

A double value, as with %f

An address of a double

%c

A character value promoted to int

An address of a char

%s

A pointer to a terminated character string

A pointer to writable character storage


For ordinary scalar variables, scanf needs their addresses so it can store results. Write scanf("%d %lf", &count, &seconds); when count is an int and seconds is a double. printf receives values instead: printf("%d %.2f\n", count, seconds);.



For output, a width sets a minimum field size, while precision controls details such as decimal places. Example: printf("%6.2f", 9.5); writes two spaces followed by 9.50. The six-character field includes padding and the decimal point. An output width does not truncate a longer number.


For input with %s, width instead limits the characters read for the token. With char name[10], %9s leaves room for the null character that scanf appends. Pass name, rather than &name, for this array destination.

Check completion before using results

On success, printf returns the number of characters written. Count padding, punctuation, spaces, and newlines, but not the format string's terminating null character:


Nwritten=Nconverted fields+Nliteral characters.N_{\text{written}} = N_{\text{converted fields}} + N_{\text{literal characters}}.


An output or encoding error produces a negative return value.


scanf instead returns the number of input items successfully assigned. With two ordinary conversions, a return value of 1 means only the first destination was assigned. A matching failure before any assignment can return 0. An input failure before the first conversion completes returns EOF; compare against EOF rather than assuming a particular numeric value.


Three connected boxes show reading input, comparing the assignment count, and using valid values.


Most conversions skip leading whitespace, but %c reads the next character directly, including a space or newline. A space before it, as in " %c", consumes leading whitespace before reading the character. This does not mean skip exactly one space.



What to remember

  • Include stdio.h for standard I/O declarations.
  • Match every conversion to its argument type and distinguish values from addresses.
  • Bound %s input to leave room for the terminating null character.
  • Check assignment counts before using input, and count characters when interpreting successful output.

Example: Read and report a sampling rate

A laboratory utility receives a sample count, an elapsed time in seconds, and a status character. Its input is 18 4.0 R followed by a newline. Assume stdio.h is included, the default C locale is active, and no input or output errors occur.


C
int samples;
double seconds;
char status;
int assigned = scanf("%d %lf %c", &samples, &seconds, &status);


The utility prints a report only if all three assignments succeed and the elapsed time is positive.


a) Determine assigned and the three stored values. Decide whether the utility should print its report.


The assignment count is the number of input items successfully stored by the ordinary conversions used here. %d reads 18 into samples. The following whitespace directive consumes the separator, and %lf reads 4.0 into the double variable seconds.


The space before %c consumes the next separator, so %c reads R rather than a space. All three assignments succeed: assigned = 3, samples = 18, seconds = 4.0 s, and status = 'R'.


The utility can print because all three assignments succeeded and the elapsed time is positive. The trailing newline remains unread.


b) The utility calculates and prints the sampling rate with this code. Determine the exact output, describing the final newline separately.


C
double rate = samples / seconds;
int written = printf("%4d %.2f %c\n", samples, rate, status);


Because seconds is a double, the division produces a floating-point result:


rate=18 samples4.0 s=4.5 samples/s.\text{rate} = \frac{18\ \text{samples}}{4.0\ \text{s}} = 4.5\ \text{samples/s}.


The calculated rate is ________, so %.2f writes 4.50. The integer 18 contains two digits. Its four-character field therefore needs ________ leading spaces, because the width includes both padding and digits.


The format also inserts one space between successive fields. The output is 18 4.50 R followed by one newline. There are two spaces before 18, one before 4.50, and one before R.


c) Determine the value stored in written.


Count each converted field first. %4d contributes four characters, %.2f contributes four, and %c contributes one. Together, the converted fields contribute ________ characters.


Next count the literal characters outside those conversions. There are two separating spaces and one newline. The format string's terminating null character is not printed.


Nwritten=4+4+1+2+1=12.N_{\text{written}} = 4 + 4 + 1 + 2 + 1 = 12.


The final value is written = 12, representing 12 characters written. This output count differs from assigned = 3, which counted successful input assignments rather than characters.

A timing utility declares int events; and double seconds;. Its input contains an integer event count followed by a duration in seconds. Assuming stdio.h is included, which call correctly stores both values?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A C command-line tool reads text, prints reports, converts integer settings, and releases dynamically allocated storage. Match each function to its purpose and the standard header that declares it.

Match each term
A.

Converts the initial numeric portion of a string to a long integer; declared in stdlib.h

B.

Writes formatted text to standard output; declared in stdio.h

C.

Releases a dynamically allocated block of storage; declared in stdlib.h

D.

Reads a bounded sequence of characters from an input stream into an array; declared in stdio.h

free

printf

strtol

fgets

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A timer displays a duration using the following C statement. Assume the default C locale and no output errors. What value is stored in written? Answer in characters as an exact integer.


C
int written = printf("T=%6.2f s\n", 3.5);

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice