Analysis of the difference between the method used by sprintf and printf in C++

  • 2020-04-02 02:58:37
  • OfStack

This article illustrates the differences between the methods used by sprintf and printf in C++. Share with you for your reference. Specific analysis is as follows:

First let's look at the prototype of printf and the prototype of sprintf in MSDN

int printf( const char *format [, argument]... );

and
int sprintf( char *buffer, const char *format [, argument] ... );

By definition, the two functions are very similar.

If you have a lot of console applications, you'll see a lot of printf, the printf function that prints the results to the screen, and the sprintf function that converts other data types to strings.
This is illustrated from the following points

(1) the first two parameters of the function are fixed, optional parameters are arbitrary, buffer is to store the string pointer or array name, fromat is a format string, as long as the format string used by printf, can be used in sprintf, format string is the essence of the function.
(2) you can first format an integer data into a string. Such as:

char str[20];
int i_arg = 12345;
sprintf(buf,"%-6d",i_arg);

(3) look at an example of a floating point type. Such as:
char str[20];
double d_arg = 3.1415926;
sprintf(str,"%6.2f",d_arg);

You can control the accuracy
(4) concatenate two strings, or concatenate multiple strings. In the output of the string, m represents the width and the number of columns occupied by the string. N is the actual number of characters. In floating point Numbers, m also represents the width and n represents the number of decimal places. Such as:
char dest[256];
char src1[] = {'a','b','c','d','e'};
char src2[] ={'1','2','3','4'};
sprintf(dest,"%.5s%.4s",src1,src2);

Can also dynamically intercept some characters of the string:
char dest[256];
char src1[] = {'a','b','c','d','e'};
char src2[] ={'1','2','3','4'};
sprintf(dest,"%.*s%.*s",2,src1,3,src2);

You can also steal valid bits of floating point types
sprintf(str,"%*.*",10,4,d_arg);

Plus, the return value of sprintf is the number of characters in the string, which is the result of strlen(STR),
You can also print the address of an argument
int i=2;
sprintf(str,"%0*x",sizeof(void *),&i);

Or use:
sprintf(str,"%p",&i);

In addition, these are all multi-byte types (ANSI) functions, and similar functions should be used for unicode types:

int wprintf( const wchar_t *format [, argument]... );
 
int swprintf( wchar_t *buffer, const wchar_t *format [, argument] ... );

The usage is very similar to the above, but of a different type,
For printf and sprintf this function is included in the < stdio.h > The header file
The sprintf and wprintf functions are included in < stdio.h > or < Wchar. H > In the header file.

Hope that the article described in the C++ programming to help you.


Related articles: