Codiqo

Learn C · lesson 31 of 60 · about 9 minutes

Building Strings Safely

Add a note to the report and name the backup file: read whole lines with fgets, build text with snprintf, and test characters with ctype.h.

What you'll learn

  • Read a line with fgets
  • Format into a buffer with snprintf
  • Use isalpha, isdigit and toupper

A note and a file name

The person running the report can type a note, like check the fans. scanf("%s") stops at the first space, so it would only get check; fgets reads the whole line. The note should start with a capital, which toupper from ctype.h gives you. Then the backup needs a file name made from text and numbers, backup-ada-day7.log, and snprintf builds it like printf does, but into an array, and never past its end.

Safer tools

  • fgets(buf, sizeof buf, stdin) reads a whole line, spaces included, and never writes more than the buffer can hold. It keeps the newline, which you usually remove.
  • snprintf(buf, sizeof buf, "...", ...) works like printf but writes into a string, again never past the end.
  • ctype.h has character tests like isalpha, isdigit, isspace and converters toupper, tolower.

Reading and shouting a line

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

int main(void) {
    char line[64];
    fgets(line, sizeof line, stdin);
    line[strcspn(line, "\n")] = '\0';

    for (int i = 0; line[i] != '\0'; i++) {
        line[i] = toupper((unsigned char)line[i]);
    }
    char message[80];
    snprintf(message, sizeof message, "%s! (%zu chars)", line, strlen(line));
    printf("%s\n", message);
    return 0;
}

Output

HELLO WORLD! (11 chars)

Tip

strcspn(line, "\n") finds the position of the newline (or the end), so setting that position to '\0' removes it.

The newline scanf leaves behind

scanf("%d", &day) reads the number and stops, leaving the Enter key's newline waiting. A fgets straight after it reads that leftover newline as an empty line and never waits for yours. The report has been using scanf, so before the note it throws away what's left of the current line: while ((ch = getchar()) != '\n' && ch != EOF) {} reads characters until it has eaten the newline.

Clearing the line before fgets

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

int main(void) {
    int day;
    scanf("%d", &day);
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF) {
    }
    char note[40];
    fgets(note, sizeof note, stdin);
    note[strcspn(note, "\n")] = '\0';
    printf("Day %d: %s\n", day, note);
    return 0;
}

Output

Day 7: check the fans

Tip

Pass ctype functions an unsigned char, as in toupper((unsigned char)c). A plain char can be negative for letters outside English, and a negative value is undefined behaviour for them.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.