C Input Numbers and Text
scanf reads floats, doubles, single chars, and words as well as whole numbers. Whole numbers used %d; each new kind of value needs its own code.
Read a float
The typed value 2.5 lands in price. printf with %f shows it as 2.500000.
#include <stdio.h>
int main() {
float price = 0.0f;
scanf("%f", &price);
printf("%f\n", price);
return 0;
}Read a double
The typed value 3.14159 lands in big. printf with %lf shows it as 3.141590.
#include <stdio.h>
int main() {
double big = 0.0;
scanf("%lf", &big);
printf("%lf\n", big);
return 0;
}Letter and word
One letter is read, then one word. The print lines show the letter first, A, then the word, Ada.
#include <stdio.h>
int main() {
char letter = '?';
char word[20] = {0};
scanf("%c", &letter);
scanf("%s", word);
printf("%c\n", letter);
printf("%s\n", word);
return 0;
}Example
#include <stdio.h>
int main() {
char word[20] = {0};
float price = 0.0f;
scanf("%s", word);
scanf("%f", &price);
printf("%s\n", word);
printf("%f\n", price);
return 0;
}Key points
- scanf("%f", &price); reads a float, a number with a point in it.
- %f is the code for a float, in scanf and in printf.
- scanf("%lf", &big); reads a double, with an l before the f.
- %lf is the code for a double, so use it for a double.
- scanf("%c", &letter); reads one single char.
- scanf("%s", word); reads one word, with no & before the name.
- A word for %s needs a char row with room for the letters and the end mark.
Word takes Apple and price takes 1.5. The print lines show the word first, then the price as 1.500000.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line reads a double into a variable named big?