- In this section we are going to study how to use scanf and printf
- C language function for standard input and output
- Defined in <stdio.h> header file
- can be used in C++
- %d : decimal
int n;
scanf("%d",&n); // input : 5
printf("%d\n",n); // output : 5
- %i : decimal
int n, m;
scanf("%d %i",&n, &m); // input : 10 10
printf("%d %d\n",n, m); // output : 10 10
scanf("%d %i",&n, &m); // input : 10 010
printf("%d %d\n",n, m); // output : 10 8
scanf("%d %i",&n, &m); // input : 10 0x10
printf("%d %d\n",n, m); // output : 10 16
- %x : hexadecimal
- %o : octal
- %s : string
char s[100];
scanf("%s", s); // input : hello world!
printf("%s\n", s); // output : hello
- %c : character
char c;
scanf("%c", &c); // input : hello world!
printf("%s\n", c); // output : h
- %f : float
- %lf : double
- %Lf : long double
- On success, the function returns the number of items of the argument list successfully filled.
while ( scanf("%d %d",&a, &b) == 2 ) // read file to the end
- scanf ignores white space and line break
for ( int i = 0; i<5; i++) {
scanf("%d", &n); // input : 10 20 30 40 50
printf("%d\n",n); // output : 10 20 30 40 50
}
for ( int i = 0; i<5; i++) {
scanf("%d", &n);// input : 10
// 20 30
// 40
// 50
printf("%d\n",n); // output : 10 20 30 40 50
}
- Reading char right after reading int
int n;
char a,b,c;
scanf("%d", &n); // input : 10
scanf("%c %c %c", &a, &b, &c); // input : A B C
printf("%d\n", n); // output : 10
printf("%c %c %c\n", a, b, c); // output :
// A B
- character variable A read '\n' instead of 'A'
int n;
char a,b,c;
scanf("%d", &n); // input : 10
scanf(" %c %c %c", &a, &b, &c); // input : A B C
printf("%d\n", n); // output : 10
printf("%c %c %c\n", a, b, c); // output : A B C
int n;
char a,b,c;
scanf("%d\n", &n); // input : 10
scanf("%c %c %c", &a, &b, &c); // input : A B C
printf("%d\n", n); // output : 10
printf("%c %c %c\n", a, b, c); // output : A B C