Beginner · Getting started with C · topic 5 of 60 · 30 min
Input and output: printf and scanf
Explanation
printf: formatted output
int qty = 3;
double price = 249.5;
char grade = 'A';
const char *city = "Pune";
printf("%d items at Rs %.2f each\n", qty, price); // 3 items at Rs 249.50 each
printf("Grade %c, city %s\n", grade, city); // Grade A, city Pune
printf("[%5d] [%-6s] [%08.3f]\n", 42, "ok", 3.14159); // [ 42] [ok ] [0003.142]
printf("%x %X %o\n", 255, 255, 8); // ff FF 10
printf("100%% done\n"); // %% prints a percent sign| Specifier | Type | Example |
|---|---|---|
| %d or %i | int | 42 |
| %u | unsigned int | 42 |
| %ld / %lld | long / long long | 9000000000 |
| %f / %.2f | double (and float, promoted) | 3.14 |
| %e | double in scientific notation | 3.140000e+00 |
| %c | char | A |
| %s | string (char *) | Pune |
| %x / %o | unsigned int in hex / octal | ff / 17 |
| %p | pointer, passed as (void *) | 0x7ffd… |
| %zu | size_t | 8 |
| %% | a literal % | % |
Escape sequences
Inside string and character literals, a backslash starts an escape: \n new line, \t tab, \\ a backslash, \" a double quote, \' a single quote, and \0 the null character (used to end strings, module 4).
scanf: reading input
int age;
double height;
printf("Age and height: ");
int got = scanf("%d %lf", &age, &height); // & gives the ADDRESS where scanf stores the value
if (got != 2) {
printf("Please enter a number and a decimal.\n");
return 1;
}
printf("Age %d, height %.2f\n", age, height);scanf needs the address of each variable (written &variable) so it can store the value there; you will understand why with pointers in module 5. It returns how many values it successfully read (or EOF at end of input). Checking that number is the only way to know the input was valid.
Common scanf traps
- Forgetting &: scanf("%d", age) passes a garbage address and usually crashes.
- The leftover newline: after scanf("%d", &n), the Enter key stays in the input, so a following scanf("%c", &ch) reads that newline. Write " %c" (with a space) to skip whitespace first.
- Unbounded strings: scanf("%s", name) can write past the end of the array (a buffer overflow). Always give a width one less than the array size: char name[20]; scanf("%19s", name);
- %s stops at the first space, so "Ravi Kumar" reads only "Ravi".
Reading a whole line: fgets
char line[100];
if (fgets(line, sizeof line, stdin) != NULL) { // reads at most 99 chars + '\0', including the newline
line[strcspn(line, "\n")] = '\0'; // remove the newline (needs <string.h>)
printf("You typed: %s\n", line);
}Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Input and output: printf and scanf · 1/6
In this lesson you will print formatted output and read input from the keyboard.
Prefer a video by a teacher? Find free videos on “c printf scanf format specifiers tutorial fgets” on YouTube ↗
In real life: A bill printer at a canteen counter
A college canteen's counter program reads an item code and quantity, checks that both were read, and prints a neatly aligned bill line using width and precision specifiers.
#include <stdio.h>
int main(void) {
int code, qty;
printf("Item code and quantity: ");
if (scanf("%d %d", &code, &qty) != 2 || qty <= 0) {
printf("Invalid input\n");
return 1;
}
double price = (code == 1) ? 15.0 : 40.0; /* 1 = tea, anything else = snack */
printf("%-8s x%-3d Rs %7.2f\n", code == 1 ? "Tea" : "Snack", qty, qty * price);
return 0;
}Practice (0/3 done)
What does printf("[%6.2f]", 3.14159); print?
Which line has the bug? 1: int n; 2: printf("Enter n: "); 3: scanf("%d", n); 4: printf("%d\n", n * 2);
Write marks.c that reads a student's name (one word, at most 29 characters) and three integer marks with scanf, checks that scanf returned the right count, and prints a report: the name left-aligned in 15 characters, the total, and the average with 2 decimals.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- The structure of a C programGetting started with C · same module
- Compiling with gccGetting started with C · same module
- Reading strings safelyStrings in C
- Pointers and functionsPointers
- StringBuilder and formattingJava Programming (Core to Spring Boot) · Arrays and strings
- Strings are char arraysStrings in C
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which scanf format reads a double?
Answer: %lf
scanf needs %lf for double (printf accepts %f).
What does scanf return?
Answer: The number of items successfully read (or EOF)
Check it against the expected count.
char name[10]; Which is safe?
Answer: scanf("%9s", name)
Leave one byte for the terminating \0.
How do you print a literal percent sign with printf?
Answer: %%
%% prints %.
fgets returns NULL when…Related
Answer: End of input is reached (or an error occurs) before reading anything
Check it before using the buffer.
Why does scanf("%d", &n) need &n?Related
Answer: So scanf can write the value into n through its address
scanf writes through the pointer.
How do you print a literal % sign with printf?Related
How many bytes does "UPI" occupy as a string literal?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Getting started with C”. The module exam comes next.
- Module 1 exam: Getting started with C · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Operators and control flow. 60 topics left in the course before the final exam.