🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Input and output: printf formats and scanf

Produce aligned tables and hexadecimal output with printf; read numbers from the user with scanf, check its return value and escape the trap of the leftover Enter in the keyboard buffer.

A measurement program does two jobs: it takes data in and shows the result in a readable way. Any program that calculates the current of a panel, converts an ADC reading to volts or prints test results as a table relies on these two jobs. In C the basic tools are printf and scanf. In this lesson we'll look at both through an engineer's eyes: "Is the output readable? Is the input reliable?"

printf format specifiers

SpecifierWhat it printsExample
%dSigned integer (int)-42
%uUnsigned integer4000
%ldlong integer3600000
%fDecimal (float and double)3.141593
%eScientific notation4.700000e-05
%cSingle characterV
%sText (string)Pano
%x / %XHexadecimal3ff / 3FF

You can put a width and precision inside a specifier: %8.2f means "a field at least 8 characters wide, 2 digits after the decimal point". The minus in %-8s left-aligns the text, and the zero in %04d fills the empty space with zeros.

#include <stdio.h>

int main(void) {
    printf("%-8s|%8s|%8s\n", "Hat", "Akim(A)", "Guc(W)");
    printf("%-8s|%8.2f|%8.1f\n", "Aydinlat", 4.35, 1000.5);
    printf("%-8s|%8.2f|%8.1f\n", "Priz", 12.0, 2760.0);
    printf("ADC ham: %04d, hex: 0x%03X\n", 77, 1023);
    printf("Bilimsel: %e\n", 0.000047);
    return 0;
}
Hat     | Akim(A)|  Guc(W)
Aydinlat|    4.35|  1000.5
Priz    |   12.00|  2760.0
ADC ham: 0077, hex: 0x3FF
Bilimsel: 4.700000e-05

Hex output is used a lot in embedded systems: 1023 is the largest value of a 10-bit ADC, and in hex it shows up as 0x3FF, that is, ten 1 bits.

Reading numbers with scanf

scanf is the reverse of printf: it decodes the text coming from the keyboard according to the specifier and writes it into a variable. The & in front of the variable gives scanf the variable's address, so scanf can write the value straight there. We'll cover addresses in depth in the pointers lesson; for now, remember the rule "in scanf, put & in front of the variable".

#include <stdio.h>

int main(void) {
    double gerilim, direnc;

    printf("Gerilim (V): ");
    scanf("%lf", &gerilim);
    printf("Direnc (ohm): ");
    scanf("%lf", &direnc);

    printf("Akim = %.3f A\n", gerilim / direnc);
    printf("Guc  = %.2f W\n", gerilim * gerilim / direnc);
    return 0;
}
Gerilim (V): 12
Direnc (ohm): 220
Akim = 0.055 A
Guc  = 0.65 W

Watch out: in printf, %f is enough for a double, but in scanf you must write %lf to read a double. %f expects a float; if you read into a double variable with %f, the value comes out corrupted.

Validate the input: scanf's return value

What happens if the user types letters instead of a number? scanf returns the number of values it read successfully. Checking it stops the program from calculating with garbage data.

#include <stdio.h>

int main(void) {
    int adc;

    printf("ADC degeri (0-1023): ");
    if (scanf("%d", &adc) != 1) {
        printf("Gecersiz giris!\n");
        return 1;
    }
    printf("Gerilim: %.3f V\n", adc * 5.0 / 1023);
    return 0;
}
ADC degeri (0-1023): 512
Gerilim: 2.502 V
ADC degeri (0-1023): abc
Gecersiz giris!

We used if here; we'll cover conditions in detail in the next lesson. The idea is simple: "if you couldn't read 1 value, stop."

Typing the same numbers on every attempt can get tiring. Write the inputs line by line into a text file (e.g. girdi.txt) and run the program as ./program < girdi.txt. This time scanf reads from the file instead of the keyboard. In the same way, ./program > sonuc.txt saves the output to a file. These redirections save a lot of time when you rerun test measurements over and over.

The buffer trap: the vanishing Enter

What you type on the keyboard first goes into a buffer. When you type a number and press Enter, the buffer holds 3\n. %d takes the number, but the newline character \n stays in the buffer. If you then read a character with %c, scanf doesn't wait for you; it takes the leftover \n:

#include <stdio.h>

int main(void) {
    int kanal;
    char birim;

    printf("Kanal no: ");
    scanf("%d", &kanal);
    printf("Birim (V/A): ");
    scanf("%c", &birim);
    printf("Kanal %d, birim '%c'\n", kanal, birim);
    return 0;
}
Kanal no: 3
Birim (V/A): Kanal 3, birim '
'

The program didn't even ask for the unit; the newline character was stored in birim. The fix is a single space: scanf(" %c", &birim);. A space before the specifier means "skip spaces, tabs and newlines first". %d and %lf already skip leading whitespace on their own; the trap is only in %c.

Common mistakes

  • Forgetting the &: scanf("%d", adc); gives scanf the variable's value (often garbage) instead of its address; the program may crash. -Wall catches this.
  • Reading a double with %f: in scanf, double = %lf, float = %f.
  • Ignoring the return value: on bad input the variable keeps its old (or garbage) value and the calculation goes silently wrong.

Exercise

Read a 10-bit ADC value from the user. If reading fails or the value is outside 0-1023, show a warning. If it is valid, print the voltage for a 5 V reference with three decimals and its ratio to full scale in the form Oran: %75.1.

Hint: use the condition adc < 0 || adc > 1023 for the range check. To put a percent sign in the text write %%; it can be followed directly by %.1f.

Solution

#include <stdio.h>

int main(void) {
    int adc;

    printf("ADC degeri: ");
    if (scanf("%d", &adc) != 1 || adc < 0 || adc > 1023) {
        printf("Gecersiz deger!\n");
        return 1;
    }
    printf("Gerilim: %.3f V\n", adc * 5.0 / 1023);
    printf("Oran: %%%.1f\n", adc * 100.0 / 1023);
    return 0;
}
ADC degeri: 768
Gerilim: 3.754 V
Oran: %75.1

You can now produce readable output and read user input safely. In the next lesson we'll learn operators and the conditions that let a program make decisions.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. Which specifier do you use to read a value into a double variable with scanf?
2. What does scanf("%d", &adc) return when the user types "abc"?
3. Why does scanf("%c", &c); skip past the user without waiting after scanf("%d", &n);?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.