C User Input and Output

C user input and output are handled by functions in <stdio.h>. printf writes formatted text to the screen and scanf or fgets read what the user types.

Formatting Output with printf

Between % and the letter you can add a width and precision. %5d pads to 5 characters, %-8s left-aligns text, %.3f shows three decimals.

#include <stdio.h>

int main(void) {
    printf("[%5d]\n", 42);
    printf("[%-8s]\n", "left");
    printf("[%8.3f]\n", 3.14159);
    return 0;
}
[   42]
[left    ]
[   3.142]

Reading Numbers with scanf

scanf needs the address of the variable, written with &, so it can store the value there. It returns how many values it successfully read.

#include <stdio.h>

int main(void) {
    int age;
    printf("Enter your age: ");
    if (scanf("%d", &age) == 1) {
        printf("Next year you will be %d\n", age + 1);
    } else {
        printf("That was not a number\n");
    }
    return 0;
}
Enter your age: 29
Next year you will be 30

Reading a Line of Text with fgets

scanf("%s") stops at the first space and can overflow the buffer. fgets reads a whole line and never writes more than the size you give it.

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

int main(void) {
    char name[50];
    printf("Full name: ");
    fgets(name, sizeof name, stdin);
    name[strcspn(name, "\n")] = '\0';  // remove the newline
    printf("Hello, %s!\n", name);
    return 0;
}
Full name: Naeem Amin
Hello, Naeem Amin!

Input Tips

  • Always check the return value of scanf.
  • Use & with scanf for int, double and char, but not for char arrays (strings).
  • Use %lf to read a double with scanf, while printf uses %f.
  • Prefer fgets for text, then convert with sscanf or strtol if needed.

Frequently asked questions

Why does scanf need & in C?

scanf must store the value into your variable, so it needs the variable's memory address. The & operator gives that address. Arrays already decay to an address, so strings do not need it.

How do I read a string with spaces in C?

Use fgets(buffer, sizeof buffer, stdin). It reads the whole line including spaces. Remove the trailing newline with strcspn.

Why is scanf skipping my input?

A previous scanf usually left a newline in the input buffer. Reading lines with fgets and parsing them avoids this problem, or add a space before %c like scanf(" %c", &ch).