Next: , Previous: , Up: Statements   [Contents]


4.9 Printf statement

printf domain : format , expression , $\dots$ , expression ;

printf domain : format , expression , $\dots$ , expression > filename ;

printf domain : format , expression , $\dots$ , expression >> filename ;

Where:

domain is an optional indexing expression which specifies the subscript domain of the printf statement;

format is a symbolic expression whose value specifies a format control string. (The colon preceding the format expression may be omitted.)

expression, $\dots$, expression are zero or more expressions whose values have to be formatted and printed. Each expression must be of numeric, symbolic, or logical type.

filename is a symbolic expression whose value specifies the name of a text file, to which the printf output should be redirected. The flag > means creating a new empty file while the flag >> means appending the output to an existing file. If no file name is specified, the output is written to the terminal.

Examples

printf 'Hello, world!\n';
printf: "x = %.3f; y = %.3f; z = %.3f\n", x, y, z > "result.txt";
printf{i in I, j in J}: "flow from %s to %s is %d\n", i, j, x[i,j];
printf{i in I} 'total flow from %s is %g\n', i, sum{j in J} x[i,j];
printf{k in K} "x[%s] = " & (if x[k] < 0 then "?" else "%g"), k, x[k];

The printf statement is similar to the display statement, however, it allows formatting the data to be written.

If the subscript domain is not specified, the printf statement is executed only once. Specifying the subscript domain causes executing the printf statement for every n-tuple in the domain set. In the latter case format and expressions may include dummy indices introduced in the corresponding indexing expression.

The format control string is a value of the symbolic expression format specified in the printf statement. It is composed of zero or more directives as follows: ordinary characters (not %), which are copied unchanged to the output stream, and conversion specifications, each of which causes evaluating corresponding expression specified in the printf statement, formatting it, and writing the resultant value to the output stream.

Conversion specifications which may be used in the format control string are the following: d, i, f, F, e, E, g, G, and s. These specifications have the same syntax and semantics as in the C programming language.


Next: , Previous: , Up: Statements   [Contents]