Printf C: description, formatting, examples

Table of contents:

Printf C: description, formatting, examples
Printf C: description, formatting, examples
Anonim

The standard C console output function is printf. Its description is contained in the header file stdio.h. With this function, you can print data or user messages to the console. The C language is case sensitive. For example, the two functions printf and scanf are different from their counterparts Printf and Scanf. All characters in the printf and scanf functions must also be written in lowercase. One of the simplest C printf examples that prints the familiar hello world greeting is:

printf c description
printf c description

Definition of the functions of the printf group in the file "stdio.h"

The file "stdio.h" refers to the standard C I/O library. Printf and similar functions are described as follows:

printf c description
printf c description

The listed functions load data from certain locations, convert it into a character string, and send it to the specified output streams.

Family of printf functions

The functions of the printf group in the C language are used for processing and formatted outputdata to the standard stream. Moreover, the printf and vprintf functions write to the standard stdout stream, the fprintf and vfprintf functions send the values of the output arguments to some given output stream, and snprintf, sprintf, vsnprintf and vsprintf write data to a character string. All of the above functions work using a format string specifying the required argument conversions for output.

printf c formatting
printf c formatting

The fprintf function writes the result to the output stream stream. The sprintf function outputs the result to a buffer, which is a character string. The function's behavior is undefined if the string to be output exceeds the size of the buffer array.

The snprintf function, like the previous one, writes data to a string buffer. The resulting character string is null-terminated unless bufsz (buffer size) is non-zero. Otherwise, if the value of bufsz is zero, then nothing is output to the buffer, and the buffer itself may well be a null pointer, but the return value (the number of bytes that should have been written) is still evaluated.

The printf_s function is basically the same as printf except for one thing. The main difference between printf_s in C and printf is that the printf_s function checks the format string for valid characters, unlike printf which only checks the format string for a null pointer.

Let's take a closer look at the printf function.

General Description

In C language printingcharacters through the standard output stream is done by calling the printf function. The printf command in C formats a set of output data and sends it to the standard output stream stdout. Values passed as function arguments are printed to the console according to the specified format string, which in turn contains two kinds of elements. The first type is the characters displayed on the screen, and the elements that define the features of the data format and are responsible for the method of presenting arguments in the output belong to the second type.

When printing variables with printf in C, special combinations of characters in the argument string are replaced with data converted according to these characters, and each data type has its own output format specifications.

Function type and return value

The printf function, which is of type int, returns an integer value indicating the number of characters printed on the screen. For example, you can assign:

int k=printf("Hello %c %d %s", 'a', 11, "everyone!"), and then by the value of the variable k it is easy to determine whether an error occurred during the output. If a negative value is returned (if the function returned "-1"), we can conclude that an error occurred during its execution.

Syntax and dependencies

To use the printf function, you need to include the "stdio.h" header file as follows:

include

The function template looks like:

int printf(const char format,…)

An ellipsis means a list of arguments to be output. The printf function can be used with a different number of arguments, but the first one is always delimited on both sides with double quotes, and each subsequent one must be separated from the previous one by a comma. What is written in double quotes and is not a format specification is printed unchanged, otherwise, if a specifier is encountered, its value type is copied.

Format specification form:

%[flags][width][.position][length]type

printf c print variables
printf c print variables

Formatting with printf to C output values

The format string specified in parentheses after the name of the called function is read only in one direction: from left to right, and the first argument specified after this line itself is displayed only if the first specification is encountered. Until the end of the format string, the specifications specified in it will initiate the conversion and printing of subsequent arguments. In a format string, the space character is treated as a normal character and is passed to the output in cases where it is not used in a format specification expression.

The "%" symbol indicates the beginning of the output format specification, followed by the format code. All fields in the specification are separate, specifying number or character formatting conditions.

The formatted output of printf in C has its own peculiarities. If the number of listed arguments exceeds the numberformat specifications, they are skipped and not output. Otherwise, if there are more format specifications than there are values in the list of arguments to be printed, the result of the function call is undefined.

To explicitly indicate which argument to use, it is possible to use "%m$" instead of "%" and "m$" instead of "", with m, an integer decimal value, indicating the position of the desired argument (indexing starts from one).

Parameters

stream Output stream for writing to file
buffer Pointer to a character string for subsequent writing to it
bufsz Determines the number of characters allowed for a record: the maximum value is bufsz-1, and a null terminator
format Pointer to a null-terminated multibyte string specifying how to interpret output arguments

Flags used in format string

Flag Description
- Align the result to the left in the output field
+ When outputting a numerical value that has a sign, force "+" to be printed before a positive value (by default, only "-" is output before a negative value)
0 For integers and floating point numbers, leading zeros are used instead of space characters to pad left digits iffield width that is greater than the length of the number. For integers, the flag is ignored if precision is explicitly specified. For other conversions using this flag, the behavior of the function is undefined. The "0" flag is ignored if the "-" flag is present
space If the output result of an expression that has a sign does not start with that sign character or is empty, then a space is added to the result. The "space" flag is ignored if the "+" flag is present
Alternate form of conversion in progress

Escape sequences

Sequence Result
\a Beep
\n New line feed
\r Return the cursor to the beginning of the line
\t Tab
\v Vertical tabs
\" Output double quote
\\ Output slash

Various format specifiers

Format Specifier Usage and description for printf C Argument type
% Writing a literal "%"
c Output one character. The argument is converted to unsigned char. When using the "l" modifier, the argument is converted to a character string unsigned char
s Printing a character string. The argument must be a pointer to the initial element of the character array char char
di Output the decimal representation of a signed integer value int
o Output octal representation without signed integer value unsigned int
xX Output a hexadecimal representation without a signed integer value. The characters "a", "b", "c", "d", "e", "f" are used to convert "x". And for the transformation "X" - "A", "B", "C", "D", "E", "F" unsigned int
u Output decimal conversion without signed integer value. If the converted value and precision are both 0, no characters are output unsigned int
fF Output the decimal representation of a floating-point number with a sign double
eE Output the exponential decimal representation of a floating point number, rounded and converted so that there is one digit before the decimal point, and the number of digits after the decimal point corresponds to the precision of the representation (by default, the precision is 6, and if 0 is specified, then the comma symbol is not output at all). The character "e" is displayed in upper or lower case depending on the conversion double
aA Output the hexadecimal representation of a floating point number double
gG Output the decimal representation of a floating point number or its decimal exponential representation depending on the value and precision double
Return the number of elements printed by the printf function. The result is written to the variable pointed to by the argument. Specification may not contain flags, field width or precision int
p Output pointer void
printf c formatting
printf c formatting

Field width modifier

The format string in printf C can contain an integer after the percent sign and before the format command. It is a field width modifier and affects the presentation of the displayed data. The smallest field width intended for a value is determined by this number, and the presence of such a modifier, if the argument is less than the field allocated to it, causes spaces or zeros to be added to the result. The default placeholder is a space character, but you can set it to zero by prefixing the width specification. The modifier specifies a minimum width, and any value that exceeds this minimum will be printed without interference. A number, for example, less than eight characters long and printed with the specification "%08d" will be zero-padded to the required eight digits.

Similarmodifiers can also specify precision or alignment options.

Precision modifier

The precision modifier is used to determine the number of decimal places to print in number representation. To add a precision modifier, put a dot after the field width specification and specify the desired precision value after it. The precision modifier is defined for "e", "f", "a", "E", "A", and "F" formats. For integers, the modifier sets the number of digits to be displayed, adding zeros to the left digit if necessary, and when displaying rational numbers, determines the required number of decimal places. For string variables, the number following the dot in the precision modifier determines the maximum length of the field when output. For example, if the format specification "%4.8s" is specified, a string will be output, the length of which is in the range of four to eight characters, if it is exceeded, the outermost characters will be omitted.

Other format modifiers

The default alignment is right-aligned, however this can be changed by putting a "-" sign after the "%". This format specification sets the left alignment.

Also, the printf function is able to distinguish between short and long integer output types. Valid specifiers are "o", "d", "u", "i", "x", and "X". The long value type is set by the "l" modifier, andshort - modifier "h". For example, when outputting a long integer and a short unsigned int, the format specifications are "%ld" and "%hu" respectively.

Length Description
h For short or unsigned short types
l For long or unsigned long types
L For type long double

Examples

1. Description of printf C and the results of calling each function:

formatted output of printf c
formatted output of printf c

2. Displaying a simple dialog message:

printf("message");

3. Program code:

printf c examples
printf c examples

Expressions given in double quotes before format specifications are printed on the screen, as well as arguments following the format string. Result of above printf C functions, output description:

printf c examples
printf c examples

This example illustrates screen output using various string formats, integer variables, symbols, and floating point numbers.

Standard scanf input function and examples of its usage

scanf c format
scanf c format

The scanf function is used to read input from the keyboard. A description of printf and scanf in C is provided in the header file "stdio.h".

scanf("format specifiers", &value1, &value2, …);

c printf format
c printf format

A simple example of working with the scanf function:

include

int main(){

int a;

float b;

scanf("%d%f", &a, &b);

}

Popular topic

Editor's choice

  • Let's build iOs apps! Overview of programs, instructions, recommendations
    Let's build iOs apps! Overview of programs, instructions, recommendations

    Today more and more people are starting to dive into the world of IT. A fairly common industry is the creation of various kinds of mobile applications. Quite a lot of different games and programs have already been developed for Android. It is because of this that many developers have begun to move to the iOS platform. This is not a very crowded industry where you can find a lot of clients and make quite a lot of money

  • Moving WordPress to another hosting: features, procedure
    Moving WordPress to another hosting: features, procedure

    Today, every person who has his own website on the Internet may face the problem that he will need to transfer the site to another hosting. There can be many different reasons for this. Of course, the most common of them is dissatisfaction with the services provided. If you can't take it anymore, then you need to act. This is a rather long procedure. If you do everything step by step, you can safely transfer the site, and not redo everything several times

  • How to pass on the rights in "SAMP RP"?
    How to pass on the rights in "SAMP RP"?

    Every person who plays online games is trying to upgrade his character and achieve many interesting things. Users who prefer SAMP try to get a driver's license even from the first level. Experienced players may not take the exam, but simply go to the instructor and buy rights from him. Of course, it will be somewhat more expensive, but this way you can save your time. How to pass on the rights to "SAMP"? Let's review this

  • How to turn off the camera on a laptop? 3 easy ways
    How to turn off the camera on a laptop? 3 easy ways

    Today, hacking has begun to actively develop in the world of information technology. An experienced hacker can get into almost any computer and get the user's information, provided, of course, the laptop is connected to the network. Recently, users have been complaining that their webcam turns on by itself. This way hackers can see where you are and what you are doing. In the future, this information can be used in completely different ways, up to the fact that you become a star on YouTube

  • Shared AppStore Account Features
    Shared AppStore Account Features

    A shared App Store account has many features. It allows users to install games and applications, as well as watch movies in high definition. Shared accounts give official access to app and game downloads for Apple devices (iPhone, iPad, iPod Touch)