Sprintf () snprintf () Usage

Source: Internet
Author: User

Sprintf () snprintf () Usage Copy content to clipboard
Code:

#include <stdio.h>
using namespace std;
int main()
{
char buf[100];
sprintf(buf, "%.*s", 4, "fluke");
printf("%s/n", buf);
memset(buf, 0, sizeof(buf));
snprintf(buf, 3, "%s", "fluke");
printf("%s/n", buf);
return 0;
}

You can see the output in two ways:

Fluk
Flu

Int snprintf (char * restrict Buf, size_t N, const char * restrict format ,...);
Function Description: a maximum of N-1 characters can be copied from the source string to the target string, followed by 0. Therefore, if the target string is n
It will not overflow.
Function return value: If the value is successful, the length of the string to be written is returned. If an error occurs, a negative value is returned.
Result1 (recommended)
# Include
# Include
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: (not recommended)
# Include
# Include
Int main ()
{
Char STR [10] = {0 ,};
Snprintf (STR, 18, "0123456789012345678 ");
Printf ("str = % s/n", STR );
Return 0;
}
Root]/root/lindatest
$./Test
Str= 01234567890123456
Test the returned values of the snprintf function:
# Include
# Include
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

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.