Input and Output in C
In questa pagina 5
Input and output are not part of the C language itself: they come from the standard library (<stdio.h>), together with string handling, storage management and math routines. Every source file that calls an I/O function needs #include <stdio.h> before the first use. File access, line functions and error output are in Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO → and Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →.
Text streams, getchar and putchar
A text stream is a sequence of lines; each line ends with a newline character.
int getchar(void); // next input character, or EOF at end of file
int putchar(int c); // writes c on stdout, returns c (or EOF on error)EOFis a symbolic constant defined in<stdio.h>.- Default input is the keyboard, default output the screen.
Redirection and pipes
program <infile # getchar reads from infile instead of the keyboard
program >outfile # putchar writes to outfile instead of the screen
otherprogram | program # stdout of otherprogram becomes stdin of programExample: lower (input converted to lower case)
#include <stdio.h>
#include <ctype.h>
int main() { /* lower: convert input to lower case */
int c;
while ((c = getchar()) != EOF)
putchar(tolower(c));
return 0;
}toloweris in<ctype.h>: converts an upper-case letter, returns every other character untouched.cis anint(notchar) so that it can holdEOF.- Functions like
getchar,putchar,tolowerare often macros: no function-call overhead per character. - The slide listing has typos (
main()without a type,int cwithout;): the code above is corrected.
Formatted output: printf
int printf(char *format, arg1, arg2, ...);It converts, formats and prints its arguments on stdout under control of format, and returns the number of characters printed. The format string holds ordinary characters (copied as they are) and conversion specifications, each converting the next argument.
A conversion specification starts with % and ends with a conversion character. In between, in order:
| Part | Meaning |
|---|---|
- |
left adjustment of the converted argument |
| number | minimum field width |
. |
separates width from precision |
| number | precision: max characters of a string, digits after the point for a float, minimum digits for an integer |
h / l |
integer is a short / a long |
If the character after % is not a valid conversion, the behavior is undefined.
Conversion characters
| Char | Argument; printed as |
|---|---|
d, i |
int; decimal number |
o |
int; unsigned octal (no leading zero) |
x, X |
int; unsigned hexadecimal (no leading 0x), with abcdef or ABCDEF |
u |
int; unsigned decimal |
c |
int; single character |
s |
char *; characters until '\0' or until the precision is reached |
f |
double; [-]m.dddddd, precision default 6 |
e, E |
double; [-]m.dddddde+/-xx, precision default 6 |
g, G |
double; uses %e if the exponent is below -4 or at least the precision, else %f; trailing zeros and point are not printed |
p |
void *; pointer (implementation-dependent) |
% |
no argument converted; prints % |
Examples (from the slides)
double d = 123456.145678901234;
double pi = 3.141592653589793;
int y = 214;
printf(":%-8.6d: - :%-6.8g: - :%-6.8e:", y, d, pi);
// :000214 : - :123456.15: - :3.14159265e+00:
printf(":%-8d: - :%-6.4g: - :%-6.8f:", y, d, pi);
// :214 : - :1.235e+05: - :3.14159265:
printf(":%2d: - :%8.4g: - :%6.8f:", y, d, pi);
// :214: - :1.235e+05: - :3.14159265:Width and precision from an argument: *
The value is taken from the next argument, which must be an int.
printf("%.*s", max, s); // at most max characters of s
printf("%*s", max, s); // s in a field at least max widePrecision on strings
Printing hello, world (12 characters), colons mark the field:
| Format | Output |
|---|---|
:%s: |
:hello, world: |
:%10s: |
:hello, world: |
:%.10s: |
:hello, wor: |
:%-10s: |
:hello, world: |
:%.15s: |
:hello, world: |
:%-15s: |
:hello, world : |
:%15.10s: |
: hello, wor: |
:%-15.10s: |
:hello, wor : |
Escape sequences and safety
\n newline, \t tab, \" double quote, \' single quote, \\ backslash.
- Number and types of arguments must match the specifiers, otherwise undefined behavior.
printf("%s", s);is safe;printf(s);fails if s contains%characters.
sprintf
int sprintf(char *buffer, char *format, arg1, arg2, ...);Same conversions as printf, but the result goes into the array buffer, which must be big enough. For safe formatting the slides recommend snprintf over sprintf, giving a maximum size to prevent buffer overflows.
Formatted input: scanf
Reading one character at a time makes it hard to interpret several values on a line (age and weight, name and number...); asking one value per line is unnatural and awkward with many fields. scanf is the input analog of printf:
int scanf(char *format, ...);It reads from stdin, interprets characters according to format, and stores results through the remaining arguments, which must be pointers.
- It stops when the format is exhausted or when input fails to match.
- It returns the number of items successfully matched and assigned; at end of file it returns
EOF, which is different from0(the next input character does not match the first specification). - The next call resumes right after the last converted character.
The format string may contain:
- blanks or tabs (not significant:
scanfskips white space while looking for values); - ordinary characters (not
%), which must match the next non-white-space input character; - conversion specifications:
%, optional*(assignment suppression: the field is read and skipped), optional maximum field width, optionalh,lorL(target width), conversion character.
An input field is a string of non-white-space characters, ending at the next white space or when the field width is exhausted. White space = blank, tab, newline, carriage return, vertical tab, form feed.
scanf conversion characters
| Char | Input data; argument type |
|---|---|
d |
decimal integer; int * |
i |
integer, may be octal (leading 0) or hex (leading 0x/0X); int * |
o |
octal integer; int * |
x |
hexadecimal integer; int * |
u |
unsigned decimal; unsigned int * |
c |
characters (default 1), white-space skipping is suppressed; to read the next non-blank character use %1s; char * |
s |
character string (not quoted), '\0' added; char * to an array long enough |
e, f, g |
floating-point number; float * |
% |
literal %, no assignment |
d, i, o, u, x may be preceded by h (pointer to short) or l (pointer to long).
Examples
// rudimentary calculator: running sum
double sum = 0, v;
while (scanf("%lf", &v) == 1)
printf("\t%.2f\n", sum += v);
// literal characters must match the input: mm/dd/yy
int day, month, year;
scanf("%d/%d/%d", &month, &day, &year);
// input like: 25 Dec 1988
int day, year;
char monthname[20];
scanf("%d %s %d", &day, monthname, &year);
// integer
int num;
scanf("%d", &num); // & passes the address of num
// two values: separated by space, tab or newline
int age; float salary;
scanf("%d %f", &age, &salary);
// string: no & (the array name is already an address)
char name[20];
scanf("%s", name);Pitfalls
- Missing
&:scanf("%d", n);instead ofscanf("%d", &n);is the most common error and is generally not detected at compile time. %sstops at the first white space: typing a full name reads only the first word.- To read a line with spaces, with a size limit, use a scan set:
if (scanf(" %19[^\n]", name) == 1) {
printf("You entered: \"%s\"\n", name);
} else {
printf("No line read (EOF or empty line)\n");
}Input Anna Rossi gives Anna Rossi; a longer line is cut at 19 characters. The leading space skips white space; %19 limits the characters stored. The slide's shorter alternative is fgets (see Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →).
%creads any character, including spaces and newlines.- Always check the return value and ask again if input was not read.
- For input of non-fixed format, read a line at a time and pick it apart with
sscanf:
int sscanf(char *string, char *format, arg1, arg2, ...); // like scanf, but reads from a stringSummary of the formatted I/O families
- printf family: formats and outputs with
%d %f %s %p; usesnprintfinstead ofsprintf. - scanf family: parses by format string, careful with buffer overflows.
- Always match the specifier to the variable type.
The same in C++ (streams)
std::cout (class std::ostream, header <iostream>) writes to stdout with the insertion operator <<; std::cin reads with the extraction operator >>.
#include <iostream>
int main() {
int age = 25;
std::cout << "I am " << age << " years old." << std::endl;
return 0;
}<<can be chained and accepts ints, floats, chars, strings.std::endlinserts a newline and flushes the buffer;'\n'only inserts the newline.std::is the namespace of the standard library;using namespace std;allows omitting it, but the explicit form avoids name conflicts in larger programs.- Escape sequences work as in C.
- Manipulators from
<iomanip>:std::setw(n)width of the next output,std::setprecision(n)digits,std::fixedfixed-point notation.
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.14159;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Pi (2 decimal places): " << pi << std::endl; // 3.14
std::cout << std::setw(10) << 42 << std::endl; // 42 in a field of width 10
return 0;
}Input:
int x, y;
std::cin >> x >> y; // >> skips leading white space, stops at the next white space
std::string fullName;
std::getline(std::cin, fullName); // whole line, spaces included, until '\n'
int age; std::string name;
std::cin >> age;
std::cin.ignore(); // discard the newline left in the buffer
std::getline(std::cin, name); // otherwise getline would read an empty stringstd::cin.ignore(n, delimiter)discards up toncharacters, stopping atdelimiter(default newline).std::cin.get(ch)reads a single character, white space included.- Validation: wrong data puts
std::cinin a fail state until cleared.
int number;
while (!(std::cin >> number)) { // invalid input
std::cin.clear(); // clear the error flag
std::cin.ignore(1000, '\n'); // discard the bad input
std::cout << "Invalid input. Please enter a valid number: ";
}std::istringstream(header<sstream>) reads from a string in memory, likesscanf:
std::string input = "42 3.14 hello";
std::istringstream iss(input);
int i; float f; std::string s;
iss >> i >> f >> s;Exercises (statements from the slides)
- Read two integers and print their sum.
- Read a double and print it with exactly 2 decimals.
- Read a full name (with spaces) and an age.
- Read an integer in hex and print it in decimal, octal and hex.
- Parse a date
dd/mm/yyyyand print it asyyyy-mm-dd. - Read N, then N doubles, and print the average with 3 decimals.
- Read a full line and count the words (separated by spaces).
Related: Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →, Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →, Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →, Lab Exercises - Loops, Arrays, Structs and IOlab exercises on loops, arrays, strings, structs, enums and file input: the statements from the course slides with their hints, plus the one solution the slides give (string reversal with an exchange function).Lab Exercises - Loops, Arrays, Structs and IO →.
Versione ripasso
- I/O is not part of the language: every file that uses it needs
#include <stdio.h>. A text stream is a sequence of lines, each ending with a newline. Default input is the keyboard, default output the screen. int getchar(void)returns the next character orEOF;int putchar(int c)writes one. Store the result ofgetcharin anint, not achar, so that it can holdEOF.
int c;
while ((c = getchar()) != EOF)
putchar(tolower(c)); /* <ctype.h> */- Redirection and pipes:
program <infile(input from a file),program >outfile(output to a file),otherprogram | program(stdout of one becomes stdin of the other). printfreturns the number of characters printed. A specification is%, then optionally-(left align), a minimum width,.precision,horl, and the conversion character.- Conversions:
d iint;o x X uunsigned octal, hex, decimal;cchar;sstring up to'\0';f e E g Gdouble;ppointer;%%a literal percent. *takes the width or precision from anintargument:printf("%.*s", max, s).%guses%eif the exponent is below -4 or at least the precision, otherwise%f, and prints no trailing zeros;%ealways shows the exponent.- Strings:
%10sright-aligns in 10 columns,%-10sleft-aligns,%.10skeeps at most 10 characters. printf("%s", s)is safe,printf(s)breaks ifscontains%. The arguments must match the specifiers, otherwise the behavior is undefined.sprintf(buffer, fmt, ...)writes into an array that must be big enough; prefersnprintfwith a size limit.scanf(fmt, ...): the arguments after the format must be pointers. It returns the number of items assigned, orEOFat end of file (which is different from 0, the first item did not match).- Scanf specifiers:
dint,iint with octal and hex allowed,uunsigned,cchar (does not skip white space),sstring (stops at white space,'\0'added),e f gfloat,%*assignment suppressed,h/lshort or long target.
double sum = 0, v;
while (scanf("%lf", &v) == 1) printf("\t%.2f\n", sum += v); // running sum
scanf("%d/%d/%d", &month, &day, &year); // literal '/' must match
scanf("%d", &num); // & gives the address
scanf("%s", name); // array: no &- To read a line with spaces, with a limit:
scanf(" %19[^\n]", name). The leading space skips white space,%19caps the characters stored.fgetsis the other option (Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →). - Typical errors:
scanf("%d", n)instead of&n(generally not detected at compile time),%sreading only the first word of a full name,%cswallowing spaces and newlines, not checking the return value ofscanf. sscanf(str, fmt, ...)parses a string the same way; useful when a line must be read first and then broken up.- C++:
std::cout << a << b,std::cin >> x(skips white space, stops at the next one),std::getline(std::cin, s)(whole line).std::endlinserts a newline and flushes,'\n'only inserts the newline.<iomanip>givessetw(n),setprecision(n),fixed. - After
std::cin >> agecallstd::cin.ignore()beforestd::getline, otherwisegetlinereads the leftover newline and returns an empty string. - Invalid input puts
std::cinin a fail state: thenstd::cin.clear()andstd::cin.ignore(1000, '\n')before reading again.std::istringstream(<sstream>) is the C++ analog ofsscanf.
See Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO → and Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →.