6.10. Input/Output

Programs aren't very useful unless you can get data into and out of them. This aspect of computing is known as Input/Output or I/O. You have already seen many examples of I/O earlier in the chapter. Every time a program contains printf or scanf, it is performing I/O, either printing data to output, or reading it from input. It is also common to read or write from files. This section covers basic aspects of I/O in C programming.

As you are now well aware, printf can be used to print strings to standard output. Variables and other values can be embedded in the string via format characters, which are preceded by a %. The following table provides the most important format characters.

Format CharactersTypes
%d, %iint, short, long
%uunsigned int
%f, %e, %gfloat, double
%schar* (string)

The format characters appear in the string passed to printf. Expressions for the values corresponding to the format characters appear after the string, separated by commas. Here is an example of printing a complex string containing several values:

int i = 5;
float f = 100.6;
char *str = "This is the winter of our discontent";

printf("Shakespeare said: \"%s\". \n\tThis, while he ate %d eggs, "
       "each weighing %f grams.\n", str, i+10, f);

If you can't fit a string on one line, you can either leave it as a single line and let it wrap around in your editor, or you can break it in two, as in this example. Two neighboring string literals are concatenated to form a single string, ...

Get Beginning Mac OS® X Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.