I/O formatting through the iostream package can be very verbose. The cstdio
package might sometimes offer better options.
- int scanf(const char *format, &arg1, &arg2, ....)
- int printf(const char *format, arg1, arg2, ....)
#include <cstdio>
using namespace std;
int main() {
char c;
while( scanf("%c", &c) != EOF ) {
printf("%c",c);
}
return 0;
}
-_-_-
Five words
in two lines.
scanf returns:
- The number of values read
- EOF at an end of file (EOF is specified in cstdio)
- 0 if no value is read
| Type specifiers
|
|
|
| %c | character |
|
|
| %d | int |
|
|
| %ld | long integer |
|
|
| %x | integer in hexadecimal (base 16) |
|
|
| %o | integer in octal (base 8) |
|
|
| %u | unsigned integer |
|
|
%f %n.mf | float or double; %n.mf asks for width n with m decimal digits (e.f., %15.5f of %.3f) |
|
|
%e %m.nf | float or double in scientific notation. |
|
|
| %s | character string (char *) |
- scanf skips over white space (blanks, tabs and newlines).
- Exception: scanf does not skip over white space for the %c type specifier
#include <cstdio>
using namespace std;
int main() {
char str[255];
while( scanf("%s", &str) != EOF ) {
printf("%s\n",str);
}
return 0;
}
-_-_-
Five
words
in
two
lines.
- A format "%*[...]" asks to skip the characters mentioned within the
brackets
- A format "%*[^...]" asks to skip the characters not mentioned within
the brackets
#include <cstdio>
using namespace std;
int main() {
char c;
scanf ("%*[^ \naeiou]");
while( scanf("%c", &c) != EOF ) {
printf("%c",c);
scanf ("%*[^\naeiou]");
}
return 0;
}
-_-_-
ieo
ioie
Additional functions.
| int getchar (void) | |
|
|
| int putchar (void) | |
|
|
| char * gets (char *s) | reads the rest of the line into
the array s;
the returned value points to
the array s;
in case of failure, the return
value is NULL |
#include <cstdio>
using namespace std;
int main() {
char input[255];
while( gets( input ) != NULL ) {
printf( "[%s] ", input );
}
return 0;
}
-_-_-
[Five words] [in two lines.]