Sprintf and printf, sprintfprintf

Source: Internet
Author: User
Tags 04x print format

Sprintf and printf, sprintfprintf

   
  Sprintf has almost the same usage as printf, but the printing destination is different. The former is printed to the string, and the latter is directly output on the command line. This also makes sprintf much more useful than printf. The following describes the usage of sprintf. Sprintf is a variable parameter function, which is defined as follows:
      Int sprintf (char * buffer, const char * format [, argument]...)   In addition to the fixed types of the first two parameters, you can take over multiple parameters later. Its essence is obviously on the second parameter: Format String.   Both printf and sprintf use formatted strings to specify the string format. Some formatspecifications starting with "%" are used inside the format string to occupy a position, the variable is provided in the variable parameter list, and the function will replace the specifier with the variable at the corresponding position to generate the string that the caller wants.   One of the most common applications of sprintf is to print Integers to strings. For example:   // Print the integer 123 into a string and save it in s.
      Sprintf (s, "% d", 123); // generate "123"
    You can specify the width. If the width is insufficient, spaces are filled on the left:
    Sprintf (s, "% 8d % 8d", 123,4567); // generate: "123 4567"   Of course, you can also align left:
    Sprintf (s, "%-8d % 8d", 123,4567); // generate: "123 4567"
    You can also print the data in hexadecimal format:
      Sprintf (s, "% 8x", 4567); // lowercase hexadecimal notation, with 8 width positions and right alignment
    Sprintf (s, "%-8X", 4568); // in hexadecimal notation, the width occupies 8 positions and is left aligned.   In this way, the hexadecimal string of an integer is easy to obtain, but when printing the hexadecimal content, we usually want an equal-width format with 0 on the left, what should we do? Simply add 0 to the number that represents the width. Sprintf (s, "% 08X", 4567); // generate: "201711d7"
You can also use this left-side 0 Complement Method to print the 10-in-hexadecimal format with "% d" above.   Pay attention to a symbol extension problem: for example, if we want to print the short INTEGER (short)-1 memory 16 into tabulation
Format: On the Win32 platform, a short type occupies 2 bytes, So we naturally want to use 4 hexadecimal numbers
Print it:
Short si =-1;
Sprintf (s, "% 04X", si );
Why is "FFFFFFFF" generated? Because spritnf is a variable parameter function, in addition to the first two parameters
The parameters are not of type security, and the function cannot simply use "% X" to know that the parameter pressure stack before the function is called.
Is it a 4-byte integer or a 2-byte short integer, so a unified 4-byte processing method is adopted,
As a result, the parameter is expanded to a 32-bit integer-1 when the stack is pressed. If the four locations are insufficient, the 32-bit integer is used.
-The 8-digit and 16-digit of 1 are printed. If you want to see the original form of si, you should let the compiler implement 0 extension instead
Symbol extension (when expansion is performed, the left side of the binary complement 0 instead of the complement sign bit ):
Sprintf (s, "% 04X", (unsigned short) si );
You can. Or:
Unsigned short si =-1;
Sprintf (s, "% 04X", si );
Sprintf and printf can also print integer strings in octal, using "% o ". Note that both hexadecimal and hexadecimal are not supported.
Negative numbers are all unsigned. In fact, they are directly hexadecimal or octal representation of the internal code of the variable.
Control floating point print format
The printing and format control of floating point numbers is another common function of sprintf. Floating Point Numbers are controlled by the format character "% f", which is guaranteed by default.
Keep the six digits after the decimal point, for example:
Sprintf (s, "% f", 3.1415926); // generate "3.141593"
But sometimes we want to control the print width and decimal places, then we should use the format "% m. nf", where the m Table
The print width. n indicates the number of digits after the decimal point. For example:
Sprintf (s, "% 10.3f", 3.1415626); // generate: "3.142"
Sprintf (s, "%-10.3f", 3.1415626); // generate: "3.142"
Sprintf (s, "%. 3f", 3.1415626); // The total width is not specified, resulting in: "3.142"
Pay attention to one question, you guess
Int I = 100;
Sprintf (s, "%. 2f", I );
What will it do? 100.00 "? Right? Try it on your own and try the following:
Sprintf (s, "%. 2f", (double) I );
The first one is definitely not the correct result. The reason is as mentioned above. When the parameter is pressed to the stack, the caller does not know
The corresponding format controller is "% f ". When a function is executed, the function itself does not know that the number pushed to the stack in the current year is an integer,
So the four bytes that saved the integer I were forcibly interpreted as a floating-point number.
However, if someone is interested in manually encoding a floating point number, you can use this method to check your hand
Is the orchestration result correct .?
Character/Ascii code comparison
We know that in C/C ++, char is also a common scalable type, in addition to the word length, it corresponds to short,
There is no essential difference between int and long types, but they are used to representing characters and strings. (Maybe we should
This type is called "byte", and now we can use byte or short to set char through typedef according to the actual situation.
)
Therefore, print a character using "% d" or "% x" to obtain its 10-or 16-digit ASCII code.
To print an integer using "% c", you can see its ASCII characters. The following section describes
The ASCII code table is printed on the screen (printf is used here. Note that "#" and "% X" are automatically used to add "0X" to the hexadecimal number"
Prefix ):
For (int I = 32; I <127; I ++ ){
Printf ("[% c]: % 3d 0x % # 04X \ n", I, I );
}
Connection string
Since the sprintf format control string can insert a variety of things, and finally "connect them into a string", it will naturally be able to connect
Concatenates strings to replace strcat in many cases, but sprintf can connect multiple strings at a time (it can also
Insert other content among them, which is flexible in short ). For example:
Char * who = "I ";
Char * whom = "CSDN ";
Sprintf (s, "% s love % s.", who, whom); // generate: "I love CSDN ."
Strcat can only connect strings (an array of characters ending with '\ 0' or a character buffer, null-terminated-string ),
But sometimes we have two character buffers, they do not end with '\ 0. For example, the number of characters returned by many third-party library functions
Groups, which are read from hardware or network transmission. They may not end with a corresponding '\ 0' after each character sequence.
Tail. If you connect directly, whether sprintf or strcat will certainly lead to illegal memory operations, and strncat also requires at least
A parameter is null-terminated-string. What should I do? We naturally remember the previous sections on printing integers and floating-point numbers.
You can specify the width, and the string is the same. For example:
Char a1 [] = {'A', 'B', 'C', 'D', 'E', 'F', 'G '};
Char a2 [] = {'h', 'I', 'J', 'k', 'l', 'M', 'n '};
If:
Sprintf (s, "% s", a1, a2); // Don't do that!
In, something went wrong. Can it be changed:
Sprintf (s, "% 7 s % 7 s", a1, a2 );
It's not good where to go. The correct one should be:
Sprintf (s, "%. 7 s %. 7 s", a1, a2); // generate: "ABCDEFGHIJKLMN"
This can be analogous to printing the "% m. nf" of floating point numbers. In "% m. ns", m indicates the occupied width (when the string length is insufficient, it is null)
If the number is exceeded, it is printed according to the actual width). n indicates the maximum number of characters that can be used from the corresponding string. Usually printing words
M is useless when it is a string, or n is used after the dot. Naturally, you can only take part of the characters before and after:
Sprintf (s, "%. 6 s %. 5 s", a1, a2); // generate: "ABCDEFHIJKL"
In many cases, we may also want the numbers in these format controllers to specify length information to be dynamic, rather
It is statically specified, because in many cases, it is only necessary for the program to obtain several characters in the character array at runtime.
The dynamic width/precision setting function is also taken into account in the implementation of sprintf. sprintf uses "*" to occupy
The position of a constant number with a specified width or accuracy. Similarly, the actual width or accuracy can be the same as that of other printed variables.
The sample is provided, so the preceding example can be changed:
Sprintf (s, "%. * s %. * s", 7, a1, 7, a2 );
Or:
Sprintf (s, "%. * s %. * s", sizeof (a1), a1, sizeof (a2), a2 );
In fact, the printed characters, integers, and floating-point numbers described above can all dynamically specify the constant values, such:
Sprintf (s, "%-* d", 4, 'A'); // generate "65"
Sprintf (s, "% #0 * X", 8,128); // generate "0X000080", "#" generate 0X
Sprintf (s, "% *. * f", 10, 2, 3.1415926); // generate "3.14"
Print address information
Sometimes, when debugging a program, we may want to view the addresses of some variables or members. Because the addresses or pointers are only 32-bit numbers, you can print the unsigned integers "% u:
Sprintf (s, "% u", & I );
However, people usually prefer to use hexadecimal instead of hexadecimal to display an address:
Sprintf (s, "% 08X", & I );
However, these are indirect methods. For address printing, sprintf provides a special "% p ":
Sprintf (s, "% p", & I );
I think it is actually equivalent:
Sprintf (s, "% 0 * x", 2 * sizeof (void *), & I );
Use sprintf's Return Value
Few people pay attention to the return values of the printf/sprintf function, but sometimes it is useful. spritnf returns the function call.
The number of characters that are finally printed to the character buffer. That is to say, after a sprinf call ends, you do not need to call it again.
Strlen knows the length of the result string. For example:
Int len = sprintf (s, "% d", I );
For a positive integer, len is equal to the 10-digit digits of the integer I.
The following is a complete example, which generates a random number between 10 [0,100) and prints them to a character array s,
Separated by commas.
# Include <stdio. h>
# Include <time. h>
# Include <stdlib. h>
Int main (){
Srand (time (0 ));
Char s [64];
Int offset = 0;
For (int I = 0; I <10; I ++ ){
Offset + = sprintf (s + offset, "% d,", rand () % 100 );
}
S [offset-1] = '\ n'; // Replace the last comma with a line break.
Printf (s );
Return 0;
}
Imagine that when you extract a record from the database and want to connect each of their fields into a word according to certain rules
This method can be used when a string is called. Theoretically, it is more efficient than the constant strcat because strcat calls
You must first find the last '\ 0' position. In the example above, we use the sprintf return value
Position.
FAQ about using sprintf
Sprintf is a variable parameter function, which often causes problems when used, and as long as there is a problem, it is usually the memory access that can cause the program to crash.
Wrong, but fortunately, the problems caused by the misuse of sprintf are serious, but it is easy to find out, there are only a few situations
The common eyes can see the error code with a few more eyes.
?? Buffer Overflow
The length of the first parameter is too short. If you don't want to say it, just give it a bigger one. Of course, it may also be the following parameter question.
It is recommended that you be careful when changing parameters. When printing a string, use the "%. ns" format to specify the maximum number of characters.
?? The first parameter is missing.
Low-level users cannot have low-level problems. They are too familiar with printf. // It is common. :. (
?? An error occurred while changing the parameter.
Generally, you forget to provide variable parameters corresponding to a certain format character, which leads to misplacement of all subsequent parameters. Check the parameters. You
Are all parameters corresponding to "*" provided? Do not map an integer to "% s". The compiler will think that you
It's so bad (the compiler is the mother of obj and exe, it should be a female, P ).
Strftime
Sprnitf also has a good cousin: strftime, which is specially used to format the time string. Its usage is similar to that of her cousin.
It is a lot of format controllers, but after all, the girl's family is fine, and she also needs to specify the maximum length of the buffer, which may be
You can shirk responsibility when a problem occurs. Here is an example:
Time_t t = time (0 );
// Generate a string in the format of "YYYY-MM-DD hh: mm: ss.
Char s [32];
Strftime (s, sizeof (s), "% Y-% m-% d % H: % M: % S", localtime (& t ));
Sprintf can also find its Zhiyin: CString: Format in MFC, and strftime naturally has her same path in MFC:
CTime: Format, which is more elegant because of the sponsorship of the object-oriented code.
The following describes printf.   Printf () can have multiple parameters, but the first parameter must be a string. Some identifiers can be added to the first string to mark the location and type of other parameters to be input. For example: Printf ("The user is % d yearsold. \ n", age ); Here, % d identifies the location and type of the parameter age to be displayed. Of course, it can also be multiple parameters.     Printf ("user info: age: % d: weight % d; height % D. \ n ", age, weight, height ); The following parameters are ordered. You have to grasp them. here, % d is used to identify Integer Variables. Next I will introduce how to identify other types of variables. % o (the letter "o" is not "0") is used to identify the octal number, and % x and % X are used to identify the hexadecimal number. x indicates that X in the hexadecimal format is in lower case, and the idea is in upper case. use % u to identify the unsigned integer variable. % ld is used to identify the long integer value. mark the floating point value with % f. % c is used to identify a numeric value. here are two examples: Printf ("The letter is % c \ n", 'A '); Printf ("The letter id % c \ n", 65 ); In the preceding two examples, the letter A is printed. Display floating point number in exponential format: Use % e or % E identifier. their differences are also case-sensitive, such as: 1.2566e + 01 and 1.2588E. display a string with the % s identifier. display the memory address pointed to by a pointer with the % p identifier. if you want to add a symbol before the value, you can add a symbol after %. for example, % + d. add a number after % to indicate the minimum number of digits to be displayed. for example, % 3d is not enough to be filled with spaces. if the above identifier is used to display 11, the result is space + 11. of course, not necessarily spaces are filled in the front. it can also be filled with numbers 0.% 03d. it is 011 when it is displayed. use % # To display the prefix, for example, the hexadecimal 0X.

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.