C Input/Output
printf()
Use printf()
to produce formatted output.
#include <stdio.h>
main()
{
int dec = 5;
char ch = 's';
float pi = 3.14;
printf("%d %f %c\n", dec, pi, ch);
}
scanf()
scanf()
is used to read formatted input from the command line.
When running code using scanf()
you should run the code from the terminal so you can input the required data.
#include <stdio.h>
main()
{
int x;
int args;
printf("Enter an integer: ");
if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
} else {
printf("Read in %d\n", x);
}
}
We’ll come to exactly what &x
means, for now it means the memory address of the variable x. scanf()
tries to read input from the command line in to the variable in the second argument, matching the format described in the first argument. If the input read doesn’t match the required type scanf()
returns zero. If it does match scanf()
returns the number of values successfully scanned and stores the value in the variable.
scanf()
can read in several values at a time.
scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);
will read in four integers separated by spaces.
We can use the format qualifiers described earlier.
char a[100];
scanf("%s",a);
will stop scanning at the first whitespace
To scan everything up to a return key press you need to use
scanf("%[^\n]", a);
which will scan till it finds a new line.
int a;
scanf("%5d", &a);
limits the input to a five digit integer.
- Previous
- Next