Common C language Functions-sprintf ()

Source: Internet
Author: User
Tags 04x sprintf truncated

#define PRGFILENAMEFORMATEX "O%04ld.txt"

sprintf (Temp,prgfilenameformatex, (Long) (Data1->pcode))

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

In addition to the first two parameter types are fixed, can be followed by any number of parameters. and the essence of it, apparently on the second parameter: Formatting the string. Both printf and sprintf use a formatted string to specify the format of the string, using some format specifier (the form specifications) that begins with "%" in the format string to occupy a position, providing the corresponding variable in the list of arguments behind it. The final function replaces that specifier with a variable of the corresponding position, producing a string that the caller wants. 1. Formatting numeric strings sprintf One of the most common applications is to print integers into strings, so SPRITNF can replace itoa in most cases. Such as:

The integer 123 is printed into a string stored in S.

sprintf (S, "%d", 123); Generate "123" to specify width, insufficient left fill space:

sprintf (S, "%8d%8d", 123, 4567); Generated: "123 4567" can of course also be left justified:

sprintf (S, "%-8d%8d", 123, 4567); Generated: "123 4567" can also be printed according to the 16 binary:

sprintf (S, "%8x", 4567); lowercase 16 Binary, Width 8 positions, right justified

sprintf (S, "%-8x", 4568); Uppercase 16 binary, Width 8 positions, left alignment so, an integer 16 binary string is easy to get, but when we print the 16 binary content, we usually want a width of the left side of the equivalent of 0, what should be done? It's easy to add a 0 to the front of the number that represents the width.

sprintf (S, "%08x", 4567); Generated: "000011d7" above with "%d" on the 10 binary printing can also use this way to the left to fill 0. Note the problem with a symbol extension: For example, if we want to print a 16 binary representation of a short integer-1 of the memory, on the Win32 platform, a shorter type is 2 bytes, so we naturally want to print it with 4 16 digits:

Short si =-1;

sprintf (S, "%04x", si); "FFFFFFFF", what's going on? Because SPRITNF is a parameter function, in addition to the previous two parameters, the following parameters are not type-safe, the function is no way to just through a "%x" to know the first function call before the argument stack is pressed in the end is a 4-byte integer or a 2-byte short integer, So take a unified 4-byte processing, resulting in the parameter stack when the symbol expansion, expanded into 32-bit integer-1, printing 4 position is not enough, the 32-bit integer 1 8-bit 16 is printed out. If you want to see the true nature of SI, then you should let the compiler do 0 extensions instead of the symbol extension (the binary left side of the extension is 0 instead of the fill sign bit):

sprintf (S, "%04x", (unsigned short) SI); You can do it. Or:

unsigned short si =-1;

sprintf (S, "%04x", si); sprintf and printf can also print integer strings in 8 binary, using "%o". Note that both 8 and 16 will not print negative numbers, which are unsigned, in fact the direct 16-or 8-binary representation of the internal code of the variable. 2. Controlling floating-point printing format floating-point number printing and formatting control is another common function of sprintf, floating-point numbers use the format character "%f" control, the default is to retain 6 digits after the decimal point, such as:

sprintf (S, "%f", 3.1415926); Generate "3.141593" but sometimes we want to control the width and scale of the print, we should use: "%M.NF" format, where m is the width of the print, n is the number of digits after the decimal point. Like what:

sprintf (S, "%10.3f", 3.1415626); Generated: "3.142"

sprintf (S, "%-10.3f", 3.1415626); Generated: "3.142"

sprintf (S, "%.3f", 3.1415626); The total width is not specified, resulting in: "3.142" notice a problem, you guess

int i = 100;

sprintf (S, "%.2f", I); What's going to happen? "100.00"? Is that right? Try it yourself, and try the following:

sprintf (S, "%.2f", (double) i); The first one is definitely not the right result, as mentioned earlier, the caller does not know that the format controller corresponding to I is a "%f" when the parameter is pressed. When the function is executed, the function itself does not know that the year was pressed into the stack is an integer, so poor to save the integer I of the 4 bytes is without any explanation forcibly as a floating-point format to explain, the whole mess. However, if someone is interested in using manually coding a floating-point number, then you can use this method to verify that the results of your manual orchestration are correct. J-character/ascii code control as we know, char is also a common type of scalable in C + + languages, except for the word length, which is not fundamentally different from Short,int,long, but is used to represent characters and strings. (Perhaps it would have been called "byte", and now it would be possible to use a byte or short to define char through a typedef, so it would be more appropriate to use "%d" or "%x" to print a character, Can derive its 10 binary or 16 ASCII code; In turn, an integer is printed with "%c" to see the ASCII character it corresponds to.

int snprintf (char *restrict buf, size_t N, const char * restrict format, ...);

Function Description: Copy n-1 characters from the source string to the target string, and then add a 0 to the back. So if the size of the target string is n, it will not overflow.

function return value: Returns the length of the string to be written if successful, or a negative value if an error occurs.

RESULT1 (Recommended usage)

#include <stdio.h>
#include <stdlib.h>

int main ()
{
Char Str[10]={0,};
snprintf (str, sizeof (STR), "0123456789012345678");
printf ("str=%s/n", str);
return 0;
}

Root]/root/lindatest
$./test
str=012345678

RESULT2: (deprecated)

#include <stdio.h>
#include <stdlib.h>

int main ()
{
Char Str[10]={0,};
snprintf (str, 18, "0123456789012345678");
printf ("str=%s/n", str);
return 0;
}

Root]/root/lindatest
$./test
str=01234567890123456

Test for the return value of the snprintf function:

#include <stdio.h>
#include <stdlib.h>

int main ()
{
Char str1[10] ={0,};
Char str2[10] ={0,};
int ret1=0,ret2=0;
ret1=snprintf (str1, sizeof (STR1), "%s", "abc");
Ret2=snprintf (STR2, 4, "%s", "AAABBBCCC");
printf ("AAABBBCCC length=%d/n", strlen ("AAABBBCCC"));
printf ("str1=%s,ret1=%d/n", str1, Ret1);
printf ("str2=%s,ret2=%d/n", str2, Ret2);
return 0;
}

[Root]/root/lindatest
$./test
AAABBBCCC length=9
Str1=abc,ret1=3
Str2=aaa,ret2=9

Explanation Size:

#include <stdio.h>
#include <stdlib.h>
int main ()
{
Char dst1[10] ={0,},dst2[10] ={0,};
Char src1[10] = "AAA", src2[15] = "AAABBBCCCDDD";
int size=sizeof (DST1);
int ret1=0, ret2=0;
ret1=snprintf (dst1, size, "str:%s", SRC1);
ret2=snprintf (dst2, size, "str:%s", SRC2);
printf ("sizeof (DST1) =%d, src1=%s,/" str:%%s/"=%s%s, dst1=%s, ret1=%d/n", sizeof (DST1), Src1, "str:", SRC1, Dst1, Ret1);
printf ("sizeof (DST2) =%d, src2=%s,/" str:%%s/"=%s%s, dst2=%s, ret2=%d/n", sizeof (DST2), Src2, "str:", SRC2, Dst2, Ret2);
return 0;
}
Root]/root/lindatest
$./test
sizeof (DST1) =10, SRC1=AAA, "str:%s" =str:aaa, DST1=STR:AAA, ret1=8
sizeof (DST2) =10, src2=aaabbbcccddd, "str:%s" =str:aaabbbcccddd, Dst2=str:aaab, ret2=17

To add, the return value of snprintf is the length of the string to be written, not the actual string size written. Such as:
Char Test[8];
int ret = snprintf (test,5, "1234567890");
printf ("%d|%s/n", ret,test);

The result of the operation is:
10|1234

Number of prototypes:
int snprintf (char *str, size_t size, const char *format, ...);

The function of size is to limit the write to Str to no more than size bytes (including the end of '/0 '). Because if the sprintf () function succeeds, it returns the number of bytes successfully written (the number of characters), and I have always thought that the snprintf () function is the same, that is, the snprintf () function does not return an integer larger than size. Look at the following section of the booklet: The functions snprintf () and vsnprintf () does not write more than size bytes (including the trailing '/0 '). If the output was truncated due to this limit then the return value is the number of characters (not including the Traili  Ng '/0 ') which would has been written to the final string if enough space had been available. Thus, a return value of size or more means that the output is truncated.If the output is truncated because of the size limit, the return value will be "if there is enough space to store the should beThe number of characters that can be output (not including the '/0 ' at the end of the string), which is equal to size or larger than size! That is, if the string that can be written is "0123456789ABCDEF" a total of 16 bits, but the size limit is 10, so that the return value of snprintf () will be -And not 10! The above also says that if the return value is equal to or greater than size, the output string is truncated (truncated).

Common C language Functions-sprintf ()

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.