printf: פלט מעוצב
איך printf קוראת את מחרוזת הפורמט משמאל לימין: טקסט שמועתק, רצפי בריחה, %d %f %c %%, כמה ערכים בקריאה אחת, רוחב ודיוק.
השיעור הזה כתוב באנגלית בלבד.
Input and output
A program talks with the user in two directions. Input (קלט) is data that enters the program: the user types on the keyboard. Output (פלט) is data that leaves the program: text that appears in the console window.
In C, the keyboard is called standard input (stdin) and the console is standard output (stdout). Two functions from stdio.h do the work:
printfwrites formatted output to the console. This lesson.scanfreads formatted input from the keyboard. Next lesson.
The whole unit uses one example: a lab console for controller boards. Each board has an ID (int board_id = 417), a measured voltage (double voltage = 4.98) and a channel letter (char channel = 'B'). The goal is a clear ticket like this one:
BOARD INTAKE
Board ID: 417
Voltage: 4.98 V
Channel: B
Status: RECORDEDAnatomy of a printf call
printf("System ready\n");Read it as a sentence: call printf and give it a format string.
printfis the function (פונקציה) name. A function is a named job that someone already wrote.printfprints formatted text.- The parentheses
( )hold the arguments (ארגומנטים): the information we give the function. "System ready\n"is the format string (מחרוזת פורמט): the text to print, in double quotes.- The semicolon
;ends the statement.
Text is printed exactly as written
printf prints exactly what is inside the quotes, and nothing more. It never adds a new line by itself:
printf("Board ready");
printf("ID: 417");Board readyID: 417Two calls did not make two lines. To end a line, you ask for it with \n:
printf("Board ready\n");
printf("ID: 417\n");Board ready
ID: 417Escape sequences
Some characters are hard to type inside the quotes. An escape sequence (רצף בריחה) is a backslash \ and one more character. It is two characters in the code and one character in the output.
| In the code | Meaning | Example | Output |
|---|---|---|---|
\n | new line | printf("A\nB\n"); | A and B on two lines |
\t | tab: jump to the next tab stop | printf("ID:\t417\n"); | ID: 417 |
\" | a double quote inside the text | printf("Status: \"READY\"\n"); | Status: "READY" |
\\ | one backslash | printf("Path: C:\\Labs\n"); | Path: C:\Labs |
Tab stops are usually every 8 columns, so after the 3 characters of ID: the tab adds 5 spaces.
The format string is a plan
The format string can also hold places for values. Each place starts with % and is called a conversion specifier (מציין המרה). The values come after the format string, separated by commas:
printf("Board %d uses channel %c\n", board_id, channel);printf reads the format string from left to right, like a plan:
- Copy the text
Boardto the console, exactly as it is. %dtakes the 1st value after the format string:board_id, so it prints417.- Copy the text
uses channel. %ctakes the 2nd value:channel, so it printsB.\nends the line.
Board 417 uses channel BEach type has its own conversion
The conversion must match the type of the value:
| Value type | Conversion | Code | Output |
|---|---|---|---|
int | %d | printf("%d", board_id); | 417 |
double (or float) | %f | printf("%f", voltage); | 4.980000 |
char | %c | printf("%c", channel); | B |
| no value | %% | printf("98%%"); | 98% |
%f prints 6 digits after the decimal point unless you ask for fewer. %% takes no value: a single % starts a conversion, so to print the percent sign itself you write it twice. Later in the course, %s prints text (strings).
Several values in one call
One call can build a whole line. The values follow the format string in the same order as the conversions: 1st conversion with the 1st value, 2nd with the 2nd, and so on. Same order, same count.
#include <stdio.h>
int main(void)
{
int board_id = 417;
double voltage = 4.98;
char channel = 'B';
printf("Board %d | %.2f V | Channel %c\n", board_id, voltage, channel);
return 0;
}Board 417 | 4.98 V | Channel B%.2f prints the voltage with two digits after the point. The next section explains it.
Width and precision
Between the % and the letter you can add a width (רוחב) and a precision (דיוק). In %8.2f, the 8 is the width and .2 is the precision:
- Precision is the number of digits after the decimal point.
printfrounds:4.96with%.1fprints5.0. - Width is the minimum number of characters. If the value is shorter,
printfadds spaces on the left. If it is longer, nothing is cut. - A
0before the width fills with zeros instead of spaces.
The bars | in these examples are part of the format string. They only show where the output starts and ends:
| Code | Output | Meaning |
|---|---|---|
printf("|%f|", voltage); | |4.980000| | default: 6 digits after the point |
printf("|%.2f|", voltage); | |4.98| | 2 digits after the point |
printf("|%8.2f|", voltage); | | 4.98| | at least 8 characters, 2 after the point |
printf("|%04d|", board_id); | |0417| | at least 4 characters, filled with zeros |
Predict the output
Write the exact output before you run it. Count the lines, include every space and punctuation mark, and apply the precision.
printf("A\nB\n");
printf("Value: %d\n", 12);
printf("Voltage: %.1f V\n", 4.96);
printf("Progress: 75%%\n");נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| input | קלט | data that enters the program |
| output | פלט | data that leaves the program |
| function | פונקציה | a named job, like printf |
| argument | ארגומנט | information given to a function, inside the parentheses |
| format string | מחרוזת פורמט | the text in quotes that printf reads from left to right |
| conversion specifier | מציין המרה | %d, %f, %c: where a value is printed |
| escape sequence | רצף בריחה | \n, \t, \", \\ |
| width | רוחב | the minimum number of characters, %8.2f |
| precision | דיוק | the number of digits after the point, %.2f |
Practice
More questions, with answers, on the practice page.