printf and scanf
More printf formatting
Format specifiers can include a width and a precision:
C
#include <stdio.h>
int main() {
printf("[%5d]\n", 42); // right-aligned in 5 characters
printf("[%-5d]\n", 42); // left-aligned
printf("[%05d]\n", 42); // padded with zeros
printf("[%.3f]\n", 3.14159);
printf("[%8.2f]\n", 3.14159);
return 0;
}To print a percent sign itself, write %% in the format string:
C
printf("Battery at 100%%\n"); // prints: Battery at 100%Widths line up columns:
C
#include <stdio.h>
int main() {
printf("%-10s %6s\n", "Item", "Price");
printf("%-10s %6.2f\n", "Coffee", 3.5);
printf("%-10s %6.2f\n", "Sandwich", 6.25);
return 0;
}%s prints a string.
Reading input with scanf
scanf reads from the keyboard. It needs the address of each variable to store into, which is what the & means:
C
#include <stdio.h>
int main() {
int age;
printf("How old are you? ");
scanf("%d", &age);
printf("Next year you'll be %d.\n", age + 1);
return 0;
}Several values at once
C
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
printf("%d + %d = %d\n", a, b, a + b);
return 0;
}Decimals and words
C
#include <stdio.h>
int main() {
float weight;
char name[30];
scanf("%f %s", &weight, name);
printf("%s weighs %.1f kg\n", name, weight);
return 0;
}A word goes into a character array (char name[30] holds up to 29 characters plus an end marker). Arrays are already addresses, so name needs no &. %s reads one word, stopping at a space.
| Specifier | Reads |
|---|---|
%d | an int |
%f | a float |
%c | a single char |
%s | one word into a char array |
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.