Salta al contenuto
Note per Studenti Input and Output in C Report

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.

c
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)
  • EOF is a symbolic constant defined in <stdio.h>.
  • Default input is the keyboard, default output the screen.

Redirection and pipes

bash
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 program

Example: lower (input converted to lower case)

c
#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;
}
  • tolower is in <ctype.h>: converts an upper-case letter, returns every other character untouched.
  • c is an int (not char) so that it can hold EOF.
  • Functions like getchar, putchar, tolower are often macros: no function-call overhead per character.
  • The slide listing has typos (main() without a type, int c without ;): the code above is corrected.

Formatted output: printf

c
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)

c
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.

c
printf("%.*s", max, s);   // at most max characters of s
printf("%*s", max, s);    // s in a field at least max wide

Precision 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

c
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:

c
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 from 0 (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: scanf skips 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, optional h, l or L (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

c
// 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 of scanf("%d", &n); is the most common error and is generally not detected at compile time.
  • %s stops 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:
c
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 →).

  • %c reads 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:
c
int sscanf(char *string, char *format, arg1, arg2, ...);   // like scanf, but reads from a string

Summary of the formatted I/O families

  • printf family: formats and outputs with %d %f %s %p; use snprintf instead of sprintf.
  • 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 >>.

cpp
#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::endl inserts 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::fixed fixed-point notation.
cpp
#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:

cpp
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 string
  • std::cin.ignore(n, delimiter) discards up to n characters, stopping at delimiter (default newline).
  • std::cin.get(ch) reads a single character, white space included.
  • Validation: wrong data puts std::cin in a fail state until cleared.
cpp
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, like sscanf:
cpp
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)

  1. Read two integers and print their sum.
  2. Read a double and print it with exactly 2 decimals.
  3. Read a full name (with spaces) and an age.
  4. Read an integer in hex and print it in decimal, octal and hex.
  5. Parse a date dd/mm/yyyy and print it as yyyy-mm-dd.
  6. Read N, then N doubles, and print the average with 3 decimals.
  7. 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 or EOF; int putchar(int c) writes one. Store the result of getchar in an int, not a char, so that it can hold EOF.
c
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).
  • printf returns the number of characters printed. A specification is %, then optionally - (left align), a minimum width, .precision, h or l, and the conversion character.
  • Conversions: d i int; o x X u unsigned octal, hex, decimal; c char; s string up to '\0'; f e E g G double; p pointer; %% a literal percent.
  • * takes the width or precision from an int argument: printf("%.*s", max, s).
  • %g uses %e if the exponent is below -4 or at least the precision, otherwise %f, and prints no trailing zeros; %e always shows the exponent.
  • Strings: %10s right-aligns in 10 columns, %-10s left-aligns, %.10s keeps at most 10 characters.
  • printf("%s", s) is safe, printf(s) breaks if s contains %. The arguments must match the specifiers, otherwise the behavior is undefined.
  • sprintf(buffer, fmt, ...) writes into an array that must be big enough; prefer snprintf with a size limit.
  • scanf(fmt, ...): the arguments after the format must be pointers. It returns the number of items assigned, or EOF at end of file (which is different from 0, the first item did not match).
  • Scanf specifiers: d int, i int with octal and hex allowed, u unsigned, c char (does not skip white space), s string (stops at white space, '\0' added), e f g float, %* assignment suppressed, h/l short or long target.
c
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 &

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 →.

Teoria collegata