Explain the function of printf output in C language

  • 2020-04-02 03:18:30
  • OfStack

C language printf() function: format output function
The printf() function is the most commonly used formatted output function, and its prototype is:


  int printf( char * format, ... );

Printf () converts and formats the data according to the parameter format string, and then outputs the result to the standard output device (display) until the string ends ('\0').

The format string can contain the following three character types:

Normal text will be printed directly ASCII control characters, such as \t, \n, etc. have specific meanings Format conversion character

Format converted to a percentage symbol (%) and its subsequent format characters. In general, each % symbol must be followed by an argument that corresponds to it (only when the %% conversion character appears is the % character directly output), and the data type to be output must be the same as its corresponding conversion character type.

The general form of printf() format conversion is as follows:


  %(flags)(width)(. prec)type

The parameters enclosed in parentheses are optional parameters, while % and type are necessary. Here are some forms of type.

1) integer

% d   Integer arguments are converted to signed decimal digits The % u   Integer arguments are converted to unsigned decimal digits % o   Integer arguments are converted to unsigned octal digits % x   The arguments to integers are converted to unsigned hexadecimal Numbers and are represented as lowercase abcdef % X   Arguments to integers are converted to unsigned hexadecimal Numbers and capitalized ABCDEF to represent floating point Numbers % f double   Type is converted to decimal digits and rounded to six decimal places below % e double   Type is printed in exponential form, with one number in front of the decimal point, six digits behind the decimal point, and a lowercase e in the exponent part %E works the same as %E, the only difference being that the exponent part will be represented by a capital E % g double   Type parameters are automatically selected to be printed in the format of %f or %e. The criteria are based on the printed value and the set number of significant digits. %G works the same as %G, the only difference being that %E format is selected when printing in exponential form.

2) characters and strings

The %c integer arguments are printed as unsigned char The parameter %s to the string is printed verbatim until a NULL character appears %p is displayed in hexadecimal format if the argument is a "void *" type pointer

There are several cases of prec:

The smallest digit of a positive integer Represents decimal places in floating point Numbers The format represents the maximum number of significant digits The %s format represents the maximum length of a string The * sign indicates that the value of the next parameter is the maximum length

Width is the minimum length of the parameter. If this column is not a value but a * symbol, then the following parameter is used as the parameter length.

There are several situations with flags

+   In general, when printing negative Numbers, printf () will print a negative sign, integer without any negative sign, this flag will make a positive sign (+) before printing positive Numbers. #   The flag will have different meanings depending on the conversion characters that follow. When the type is o (such as %#o), an extra o is printed before the octal value is printed. Before type x (%#x), more '0x' is printed before hexadecimal Numbers, and decimal points are forced before type e, e, f, g, or g. Both the decimal point and the zero at the end of the decimal place are retained when the type is g or before g. 0   When there is a specified parameter, the argument with no number is followed by 0. This flag is turned off by default, so blank characters are typically printed.

Returns the number of characters written on success.

If a write error occurs, the file error flag (detectable by ferror()) is set and a negative number is returned.

If a multi-byte character is encoded incorrectly while writing a wide character, errno is set to EILSEQ and returns a negative number.

Printf (format,... ) is equivalent to fprintf(stdout, format,...) , refer to the fprintf() function for more information.

Outputs integers, floating point Numbers, and strings, respectively.


#include<stdio.h>
int main(void)
{
  int a=1;
  float b=5.0;
  char str[100]= "";
  scanf("%c %c %c",&a,&b,str);
  
  printf("int is:%dn",a);
  
  printf("float is:%fn",b);
  
  printf("char is:%sn",str);
  
  return 0;
}

Output results:
[operation result]


1 4.4 fs
int is:1
float is:4.400000
char is:fs

The example starts by waiting for the user to enter an integer floating point number and a string, and then calls the function printf() to output it in the corresponding format.

For example, output data in more formats.


#include <stdio.h>
int main()
{
  printf ("Characters: %c %c n", 'a', 65);
  printf ("Decimals: %d %ldn", 1977, 650000L);
  printf ("Preceding with blanks: %10d n", 1977);
  printf ("Preceding with zeros: %010d n", 1977);
  printf ("Some different radices: %d %x %o %#x %#o n", 100, 100, 100, 100, 100);
  printf ("floats: %4.2f %+.0e %E n", 3.1416, 3.1416, 3.1416);
  printf ("Width trick: %*d n", 5, 10);
  printf ("%s n", "A string");
  return 0;
}

Output results:


Characters: a A
Decimals: 1977 650000
Preceding with blanks:    1977
Preceding with zeros: 0000001977
Some different radices: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick:  10
A string

C language fprintf() function: output function (format output data to file)
The header file:


#include <stdio.h>

Definition function:


int fprintf(FILE * stream, const char * format, ...);

Function description: fprintf() converts and formats the data according to the parameter format string, and then outputs the result to the file specified by the parameter stream until the string ends ('\0').

Return value: refer to printf() for the format of the parameter format string. Return the actual number of characters output on success, -1 on failure, and the error is in errno.

sample


#include <stdio.h>
main()
{
  int i = 150;
  int j = -100;
  double k = 3.14159;
  fprintf(stdout, "%d %f %x n", j, k, i);
  fprintf(stdout, "%2d %*dn", i, 2, i);
}

Perform:


-100 3.141590 96
150 150

C sprintf() : writes formatted data to a string
The header file:


#include <stdio.h>

The sprintf() function is used to write formatted data to a string. The prototype is:


int sprintf(char *str, char * format [, argument, ...]);

[parameter] STR is the string to be written; Format is a formatted string, the same as the printf() function; Argument is a variable.

In addition to the first two parameter types fixed, can be followed by any number of parameters. The essence, of course, lies in the second parameter, the formatted string. Printf () and sprintf () USES a formatted string to specify the format of the string, in the format string used within some starting with "%" format specifier (the format specifications) to occupy a position in the back and provide the corresponding variables in the list, the final function with the corresponding position of the variable to replace the specifiers, produce a caller to a string.

One of the most common USES of sprintf() is to print integers into strings, such as:

      Sprintf (s, "% d", 123);   // print the integer 123 as a string and save it in s       Sprintf (s, "% x 8", 4567);   // lower case hexadecimal, 8 widths, right aligned

Sprintf prints a formatted string to a destination string, while printf prints a formatted string to the screen. The first parameter of sprintf should be the destination string. If this parameter is not specified, the program will be shut down. The prompt.

Sprintf () converts and formats the data according to the parameter format string, and then copies the result into an array of strings referred to by the parameter STR until the string ends ('\0'). Refer to printf() for the format of the parameter format string.

[return value] returns the length of the parameter STR string on success, -1 on failure, and the reason for the error is in errno.

Note: the C language does not detect the length of an array when operating on it. If the length of STR is insufficient, sprintf() can easily cause a buffer overflow, with unintended consequences. Hackers often exploit this vulnerability to attack seemingly secure systems. Look at the following code:


#include <stdio.h>
main()
{
  char buf[10];
  sprintf(buf, "The length of the string is more than 10");
  printf("%s", buf);
}

Compile and run, print "The length of The string is more than 10" on The screen, and The system indicates that The program has stopped. The reason is that the length of the string to be written exceeds the length of the buf, causing a buffer overflow.

Using snprintf() instead of sprintf() will solve this problem nicely.

Print the ASCII value of the letter a.


#include <stdio.h>
main()
{
  char a = 'a';
  char buf[80];
  sprintf(buf, "The ASCII code of a is %d.", a);
  printf("%s", buf);
}

Operation results:


The ASCII code of a is 97.

Another example is to generate 10 random Numbers within 100 and output them.


#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
  char str[100];
  int offset =0;
  int i=0;
  srand(time(0)); //* random seeds
  for(i = 0;i<10;i++)
  {
    offset+=sprintf(str+offset,"%d,",rand()%100); //The formatted data is written to a string
  }
  str[offset-1]='n';
  printf(str);
  return 0;
}

Operation results:


74,43,95,95,44,90,70,23,66,84

The example USES a new function, srand(), which generates random Numbers. The most complex part of the example is that each time the function sprintf() is called in the for loop to write data to a character array, STR +foffset is the starting address of each write. The end result is that all generated random data is stored in the array as integers.


Related articles: