Detailed explanation of the related functions of printf output in C language _c language

Source: Internet
Author: User
Tags control characters lowercase numeric value random seed sprintf

C language printf () function: Format output function
the printf () function is the most commonly used format 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 results to the standard output device (monitor) until the end of the string ('? ') appears.

The parameter format string can contain the following three types of characters:

    1. Generic text that will be directly output
    2. ASCII control characters, such as \ t, \ n, and so on have a specific meaning
    3. Format conversion characters

The format is converted to a percent symbol (%) and a later format character. In general, each% symbol must subsequently have a parameter that echoes it (only the% character will be printed directly when the percent conversion character appears), and the data type to be exported has to be the same as the corresponding conversion character type.

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

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

The parameters enclosed in parentheses are optional, and% and type are necessary, and several forms of type are described below.

1) Integer

    • The parameters of%d integers are converted to signed decimal digits
    • %u integer arguments are converted to unsigned decimal digits
    • %o The parameters of an integer are converted to unsigned octal digits
    • The parameters of the%x integer are converted to unsigned hexadecimal digits and are represented in lowercase abcdef
    • The parameters of the%x integer are converted to unsigned hexadecimal digits and the floating-point number is represented in uppercase ABCdef
    • The parameters of the%f double are converted to decimal digits and taken to six digits below the decimal point, rounded
    • The parameters of the%e double are printed exponentially, with a number in front of the decimal point, six digits after the decimal point, and in the exponent portion in lowercase e.
    • %E is the same as%E, the only difference is that the exponent portion will be expressed in uppercase E
    • The parameters of the%g double are automatically selected to be printed in%f or%e format, based on the number of printed values and the amount of significant digits that are set.
    • %G is the same as%G, the only difference is that the%e format is selected when printed in exponential form.

2 Characters and strings

    • The parameters of the%c integer are converted to unsigned char to print out
    • %s The argument to the string is output verbatim until the null character is present
    • %p If the argument is a "void *" pointer, the hexadecimal format is used to display

Prec has several conditions:

    • The minimum number of digits of a positive integer
    • To represent the number of decimal places in floating-point numbers
    • Format represents the maximum number of significant digits
    • Represents the maximum length of a string in the%s format
    • The x symbol represents the maximum length of the next parameter value.

Width is the minimum length of the parameter, if this column is not a numeric value, but a * symbol, the following parameter is represented as the length of the parameter.

Flags have the following situations

    • + generally when printing a negative number, printf () will print a minus sign, the integer without any minus sign, this flag RCAs so that before printing positive numbers a plus (+).
    • # This flag RCAs has different meanings depending on the characters that are converted later. When the type is O (such as% #o), an O is printed before the octal value is printed. Before the type X (% #x) prints the ' 0x ' before the hexadecimal number is printed, forcing the value to print the decimal point before the form is E, E, F, G, or G. Keep the decimal point and the end of the scale at 0 at the same time before the type is G or G.
    • 0 when there are specified parameters, the parameters of the innumerable words will be up to 0. By default, this flag is turned off, so white space characters are generally printed.

Return value succeeds returns the number of characters written.

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

If a multibyte character encoding error occurs while writing a wide character, then errno is set to EILSEQ and a negative number is returned.

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

"Instance" 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);
  /* Demonstrates integer
  /printf separately ("int is:%d\n", a);
  /* Demo floating-point number
  /printf ("Float is:%f\n", b) respectively;
  /* Demo string
  /printf ("Char is:%s\n", str) respectively;
  
  return 0;
}

Output results:
"Run Results"

1 4.4 fs
int is:1
float is:4.400000
Char Is:fs

The example first waits for the user to enter an integer floating-point number and a string, and then calls the function printf () to output in the corresponding format.

For example, output more data in a format.

#include <stdio.h>
int main ()
{
  printf ("Characters:%c%c", ' a ',);
  printf ("Decimals:%d%ld\n", 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", MB, m, MB);
  printf ("Floats:%4.2f%+.0e%E \ n", 3.1416, 3.1416, 3.1416);
  printf ("Width trick:%*d \ n", 5);
  printf ("%s \ n", "A string");
  return 0;
}

Output results:

Characters:a a
decimals:1977 650000
preceding with blanks:    1977
preceding with zeros:0000001977< C19/>some different radices:100 144 0x64 0144 floats:3.14
+3e+000 3.141600E+000
Width trick:
A string

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

#include <stdio.h>

To define a 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 end of the string ('? ') appears.

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

Example

#include <stdio.h>
Main ()
{
  int i =;
  int j = -100;
  Double k = 3.14159;
  fprintf (stdout, "%d%f%x \ n", J, K, i);
  fprintf (stdout, "%2d%*d\n", I, 2, i);
}

Perform:

-100 3.141590
150 150

C language sprintf () function: Writes formatted data to a string
header file:

#include <stdio.h>

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

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

The parameter str is the string to be written; format is the formatted string, the same as the printf () function; argument is a variable.

In addition to the first two parameter types are fixed, any number of parameters can be followed. And its essence, obviously, is on the second parameter, the format string. Both printf () and sprintf () use a formatted string to specify the format of the string, to occupy a position within the format string, with a format specifier that starts with "%" (the form specifications), and to provide the corresponding variable in the argument list that is behind it. The final function replaces the descriptor with the corresponding position variable to produce a string that the caller wants.

One of the most common uses of sprintf () is to print integers to a string, such as:

    • sprintf (S, "%d", 123); Print integer 123 as a string to save in s
    • sprintf (S, "%8x", 4567); lowercase 16, width to 8 positions, right aligned

The role of sprintf is to output a formatted string to a destination string, while printf prints a formatted string to the screen. The first parameter of the sprintf should be the destination string, and if this argument is not specified, the prompt for "illegal operation of the program, impending shutdown ..." occurs during execution.

sprintf () Converts and formats the data according to the parameter format string, and then copies the result to the string array that argument STR refers to until the end of the string (' "). Refer to printf () for the format of the parameter format string.

"Return value" succeeds returns the parameter str string length, Failure returns 1, and the reason for the error is stored in errno.

Note: The C language does not detect the length of the array, if the length of STR is not enough, sprintf () is likely to cause a buffer overflow, with unintended consequences, hackers often use this vulnerability to attack a seemingly secure system. Take a look at the following code:

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

Compiled and run, the screen outputs "the length of the string is more than 10", while the system prompts the program has stopped. The reason is that the length of the string to be written exceeds the length of the buf, resulting in a buffer overflow.

Using snprintf () instead of sprintf () will be a good solution to this problem.

"Instance" prints 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);
}

Run Result:

The ASCII code of A is 97.

Another example is to produce a random number within 10 100 and output.

#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 seed
  for (i = 0;i<10;i++)
  {
    offset+=sprintf (Str+offset, "%d,", Rand ()%100);//formatted data write String
  }
  str[offset-1]= ' \ n ';
  printf (str);
  return 0;
}

Run Result:

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

The example uses a new function Srand (), which produces random numbers. The most complex part of the example is the sprintf () for each function in the For loop that writes data to a character array, str+foffset the start address for each write of the data, and the final result is that all of the resulting random data is stored as integers in the array.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.