LABORATORY 03

Console Input/Output Operations

Duration: 2 hours Library: stdio.h Previous: Laboratory 2 PDF handout RO versiunea română

In C, input/output operations are not part of the language: there are no dedicated statements, only functions added through the standard library. This separation gives flexibility, but shifts onto the programmer the responsibility of correctly specifying the format of the data.

1Lab objectives

  • Understanding the concept of a stream and the five predefined logical devices
  • Using character-level read/write functions
  • Reading and printing character strings
  • Correctly using format specifiers in printf and scanf
  • Recognizing and avoiding the classic pitfalls of the scanf function

2Standard streams

keyboardcharacter streamcininput buffervariableknown typekeystrokesthe >> operatorscreendisplayed textcoutoutput buffervariablethe << operatorflushing the buffer
Fig. - The two standard streams. Data does not go directly from the keyboard to the variable: a buffer sits between them, which explains why unread leftover characters affect the next read.

Transfers to and from physical devices happen through logical devices called streams. There are two categories: text streams, which transfer characters organized into lines, and binary streams, which transfer bytes with no imposed structure.

StreamTypeAssociated withCan be redirected?
stdintextthe keyboard - standard inputyes
stdouttextthe monitor - standard outputyes
stderrtextthe monitor - the error outputyes
stdprnbinarythe printer (DOS PRN device)no
stdauxbinaryauxiliary input/output (DOS AUX)no
Why stderr exists separately from stdoutError messages travel on a separate stream, so that when redirecting output to a file (program > result.txt) errors still show up on the screen, instead of being hidden in the file.

3Character-level operations

FunctionRoleNotes
int getchar(void)reads a character from stdinwaits for Enter; returns EOF at end of file
int getch(void)reads a character with no echodoes not wait for Enter; specific to conio.h, non-portable
int getche(void)reads a character with echo on screendoes not wait for Enter; non-portable
int putchar(int c)writes a character to stdoutreturns the character written
Why it returns int, not chargetchar() must be able to signal the end of the stream through the value EOF (usually −1), which does not fit in the unsigned char range. If the result is stored in a char, the test c != EOF may never work.

4String operations

FunctionRoleRisk
gets(s)reads an entire line, including spacesdangerous - does not limit the length; removed from the standard
fgets(s, n, stdin)reads at most n−1 characterssafe; keeps the trailing '\n' character
puts(s)prints a string and adds a newline-
scanf("%s", s)reads a word (stops at whitespace)cannot read sentences with spaces
Practical ruleAlways use fgets instead of gets. To remove the leftover newline character: s[strcspn(s, "\n")] = '\0';

5Formatted input/output

The structure of a specifier

general form
%[flag][width][.precision][modifier]type

   %-8.3f
   │││ │ └── type: f = real
   ││└─┴──── precision: 3 decimals
   │└─────── minimum width: 8 characters
   └──────── flag: - = left alignment
SpecifierData typeExample output
%d, %iint-42
%uunsigned int4294967254
%ffloat / double3.141593
%.2freal with 2 decimals3.14
%escientific notation3.141593e+00
%ccharA
%scharacter stringtext
%x, %Xhexadecimalff / FF
%ooctal377
%paddress (pointer)0x7ffd3a2c
%%a literal percent character%

6Specifier explorer

Choose a specifier and a value, then watch exactly what printf prints. Try mismatched combinations - for example %c with the value 65 - to understand why the compiler does not warn you.

printf - specifier, value, result

7Reading pitfalls

1. Missing the & operator in scanf scanf("%d", n); instead of scanf("%d", &n); passes the value of the variable instead of its address. The program compiles, but crashes badly at run time.
2. The Enter character left in the buffer After scanf("%d", &n);, the Enter key is left unread in stdin. An immediately following scanf("%c", &c); will pick up that '\n', not the intended character. Solution: scanf(" %c", &c); - the space in the format skips over whitespace characters.
3. Mismatched specifier printf("%d", 3.14); produces no compile error, but prints a meaningless value, because it interprets the bits of a double as an int.
4. Invalid input data If the user types letters when a number is expected, scanf returns 0 and leaves the text in the buffer, which can lead to an infinite loop. The value returned by scanf says how many values it actually read: 1 means success, 0 means something other than a number was in front. The safe_read.c program below prints it; how to react to it, with if and while, comes in labs 5 and 6.

8Source code

characters.c - reading character by character
#include <stdio.h>

int main(void)
{
    int c1, c2, c3;         // int, NOT char: getchar() can also return EOF

    printf("Type three characters: ");
    c1 = getchar();         // each call takes the next character from stdin
    c2 = getchar();
    c3 = getchar();

    printf("First:  '%c' has code %d\n", c1, c1);
    printf("Second: '%c' has code %d\n", c2, c2);
    printf("Third:  '%c' has code %d\n", c3, c3);

    putchar(c1);            // putchar prints a single character
    putchar('\n');

    printf("The constant EOF is %d - it does not fit in an unsigned char,\n", EOF);
    printf("which is why the result of getchar() is kept in an int.\n");
    return 0;
}
safe_read.c - safe reading and checking scanf
#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[50];
    int age = 0;
    int count;

    printf("Full name: ");
    fgets(name, sizeof(name), stdin);           // safe: limits the length
    name[strcspn(name, "\n")] = '\0';           // remove the newline

    printf("Age: ");
    count = scanf("%d", &age);                  // how many values it managed to read
    printf("scanf returned %d\n", count);       // 1 = a number was read, 0 = not

    printf("\n%-20s %3d years old\n", name, age);
    return 0;
}
formatting.c - an aligned table
#include <stdio.h>

int main(void)
{
    printf("%-12s %8s %10s\n", "Product", "Qty", "Price");
    printf("--------------------------------\n");
    printf("%-12s %8d %10.2f\n", "Resistor",   120,  0.15);
    printf("%-12s %8d %10.2f\n", "Capacitor",  45,  0.80);
    printf("%-12s %8d %10.2f\n", "Microcontroller", 8, 24.50);

    // the same number, in different bases
    int v = 255;
    printf("\n%d in decimal = %o in octal = %X in hex\n", v, v, v);

    // printing a literal percent sign
    printf("Progress: %d%%\n", 75);

    return 0;
}

9Code workshop

Output formatting is learned by experimenting. Change the numbers inside the specifiers (%8.3f, %-12s) and watch the columns move.

Format specifiers, seen at work
#include <stdio.h>

int main(void)
{
    int    n = 42;
    double x = 3.14159265;
    char   c = 'Q';
    char   s[] = "text";

    printf("[%d]      plain integer\n", n);
    printf("[%8d]  width 8, right aligned\n", n);
    printf("[%-8d]  width 8, left aligned\n", n);
    printf("[%08d]  zero padded\n", n);

    printf("\n[%f]      default: 6 decimals\n", x);
    printf("[%.2f]        two decimals\n", x);
    printf("[%10.3f]  width 10, three decimals\n", x);

    printf("\n[%c] [%s] [%x in hex] [%o in octal]\n", c, s, n, n);
    return 0;
}
Reading from the keyboard - exercise
#include <stdio.h>

int main(void)
{
    char   name[30];
    int    age;
    double average;

    printf("Name: ");
    scanf("%s", name);

    /* Also read the age (integer) and the average (double).
       Careful: with scanf, numeric variables need & */

    printf("\n%-12s %3d years old   average %.2f\n", name, age, average);
    return 0;
}
Try thisThe input data field above stands in for the keyboard: each value there is picked up by one scanf, in order. In a real program, the user would type them one at a time.

10Exercises with automatic checking

This is where you write the code. The ✓ Check button runs your program on several data sets and shows you right away where the result differs. At the end you submit the track you chose, and the instructor grades it automatically.

Every exercise has the program already started, and the comments tell you what is left to add. Write the code, press ✓ Check and read what each failed test says. If you get stuck, open the hints one at a time. You may also print messages for the user (such as Enter n:); the test looks at what you print at the end.

P1

A personal greeting

Read a first name (a single word) and print Hello, <name>!.

inputAna
outputHello, Ana!
#include <stdio.h>

int main(void)
{
    char name[50];

    /* 1. Read the word with scanf("%49s", name);  - no & for an array!
       2. Print it with printf("Hello, %s!\n", name); */

    return 0;
}
P2

A whole line with fgets

Read a full name, which may contain spaces, with fgets. Print it between square brackets, followed by its number of characters (without the newline).

inputIon Popescu
output[Ion Popescu] 11
#include <stdio.h>
#include <string.h>

int main(void)
{
    char s[100];
    fgets(s, sizeof s, stdin);

    /* fgets also keeps the '\n' at the end of the line. Remove it:
           s[strcspn(s, "\n")] = '\0';
       then print: printf("[%s] %d\n", s, (int)strlen(s)); */

    return 0;
}
P3

Number bases with a prefix

Read a positive integer n. Print it in decimal, in octal with the prefix 0 and in hexadecimal with the prefix 0x and capital letters for the digits, for example 255 0377 0xFF.

input255
output255 0377 0xFF
#include <stdio.h>

int main(void)
{
    int n;
    scanf("%d", &n);

    /* %o and %X print in octal and in hexadecimal with capital letters.
       You can write the prefixes directly in the text: "0%o", "0x%X". */

    return 0;
}
P4

An aligned table row

Read a name (one word) and a real grade. Print a table row: the name left-aligned in 10 characters, then |, then the grade right-aligned in 6 characters with two decimals. Example: Ana | 9.50.

Spacing matters here: the output is compared character by character (only trailing spaces are ignored).

inputAna 9.5
outputAna | 9.50
#include <stdio.h>

int main(void)
{
    char name[30];
    double grade;
    scanf("%29s %lf", name, &grade);

    /* The width goes between % and the letter: %10s takes 10 characters.
       A minus aligns to the left: %-10s. For the grade: %6.2f. */

    return 0;
}
P5

The leftover Enter trap

The first line holds an integer n and the second a character c. Print n=<n> c=<c>.

input5 x
outputn=5 c=x
#include <stdio.h>

int main(void)
{
    int n;
    char c;
    scanf("%d", &n);
    scanf("%c", &c);   /* something is wrong here - run it and see */
    printf("n=%d c=%c\n", n, c);
    return 0;
}

Problems start from an empty main. The output format must be followed exactly (spaces and newlines do not matter unless the statement says otherwise), so do not print prompts. The visible tests cover only the simple cases; grading also runs hidden tests chosen to catch the edge cases.

A1

An invoice with three products

Read exactly three lines name quantity price (the name is one word, the quantity an integer, the price a real number). Print each product on one line: the name left-aligned in 12 characters, the quantity in 4, the text x , the price in 7 characters with two decimals, = and the value in 9 characters with two decimals. At the end print TOTAL left-aligned in 12 characters and the total in 26 characters, with two decimals. (No loops: they come in Lab 6.)

Spacing matters here: the output is compared character by character (only trailing spaces are ignored).

inputpaine 2 3.5 lapte 1 7.99 mere 3 2.4
outputpaine 2 x 3.50 = 7.00 lapte 1 x 7.99 = 7.99 mere 3 x 2.40 = 7.20 TOTAL 22.19
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A2

A date in several formats

Read a date written day.month.year (for example 5.3.2026). Print it on one line in the ISO format yyyy-mm-dd and then in the US format mm/dd/yyyy, with leading zeros. Example: 2026-03-05 03/05/2026.

input5.3.2026
output2026-03-05 03/05/2026
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A3

Name and initials

Read a first name and a last name (one word each, at least two letters long). On one line print: the last name, a comma, the initial of the first name followed by a dot, then, in parentheses, the total number of letters. Example: for Ion Popescu print Popescu, I. (10 letters).

inputIon Popescu
outputPopescu, I. (10 letters)
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}
A4

One number, five formats

Read a real number x. Print it on five lines: with a sign and three decimals (%+.3f), in scientific notation with three decimals, in 10 characters right-aligned with two decimals and framed by |, then the same but left-aligned, and finally the integer part padded with zeros up to 6 digits.

Spacing matters here: the output is compared character by character (only trailing spaces are ignored).

input3.14159
output+3.142 3.142e+00 | 3.14| |3.14 | 000003
#include <stdio.h>

int main(void)
{
    /* write your solution here */

    return 0;
}

11Work tasks

  • Write a program that reads characters until EOF and counts the letters, digits, and spaces.
  • Read a full name (with spaces) using fgets and print it with puts.
  • Reproduce the leftover-Enter-in-the-buffer trap, then fix it with " %c".
  • Print the number 255 in decimal, octal, and hexadecimal, in a single printf.
  • Build an aligned table with three columns, using explicit widths and alignments.
  • Implement robust reading of an integer, with retry on invalid data.
  • Test what printf("%d", 3.14) prints and explain the result.

12Extended application

ExtensionWrite a small "text analyzer": the program reads a sentence and prints the number of words, the longest word, the number of vowels and consonants, plus the frequency of each letter as a histogram of asterisks. Use only functions from stdio.h and ctype.h.

13Review questions

14Resources