sprintf的用法

先来看个程序

#include <stdio.h>
void main( void )
{
    char  buffer[200], s[] = "computer", c = 'l';
    int   i = 35, j = 0;
    float fp = 1.7320534f;
   
    j  = sprintf( buffer, "String:%s/n", s);
    cout<<j<<endl;                  // j = 16
    cout<<buffer<<endl;

    j += sprintf( buffer + j, "Character:%c/n", c);
    cout<<j<<endl;                    // j = 16 + 12 = 28
    cout<<buffer<<endl;
   
    j += sprintf( buffer + j, "/tInteger:%d/n", i);
    cout<<j<<endl;                // j = 28 + 12 = 40 此处%d格式化后占2bytes
    cout<<buffer<<endl;
   
    j += sprintf( buffer + j, "/tReal:%f", fp);
    cout<<j<<endl;               // j = 40 + 14 此处%f格式化后占8bytes                     
   
    printf( "Output:/n%s/ncharacter count = %d/n", buffer, j );
}


sprintf, swprintf <script src="ms-its:dsmsdn.chm::/html/msdn_header.js"></script> @import url(MS-ITS:dsmsdn.chm::/html/msdn_ie4.css);

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

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

sprintf, swprintf <script src="ms-its:dsmsdn.chm::/html/msdn_header.js"></script> @import url(MS-ITS:dsmsdn.chm::/html/msdn_ie4.css);

sprintf returns the number of bytes stored in buffer, not counting the terminating null character. swprintf returns the number of wide characters stored in buffer, not counting the terminating null wide character.

sprintf, swprintf <script src="ms-its:dsmsdn.chm::/html/msdn_header.js"></script> @import url(MS-ITS:dsmsdn.chm::/html/msdn_ie4.css);

Parameters

buffer

Storage location for output

format

Format-control string

argument

Optional arguments


sprintf的返回值是不包括空白终止符的字符个数,但是经过sprintf格式化后,int占2个字节,float占8个字节。。。。

再看下面程序

int main()
{
    char s[]  = "computer";
    cout<<s<<endl;
    cout<<sizeof(s)<<endl;  //9

    char s1[100];
    char* p= "haha";
    int j = sprintf(s1, "/t%s", p);
    cout<<s1<<endl;             //  haha
    cout<<j<<endl;               // 5
   
    return 0;
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值