sprintf基本用法

学过c语言的人都用过printf()这个函数,但是对于它的"兄弟"函数sprintf()这个函数就很少有人知道了,但是它的功能比printf()还要强大!

由于它比较强大,目前我也只理解了一小部分,现在先把所学的整理下来,以后有时间再去更新,研究.

废话不多说,直接上代码

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=0;
int main()
{
    char str[100];

    sprintf(str,"%d",1234);
    cout<<"十进制1:"<<str<<endl;//1234

    sprintf(str,"% 10d",1234);
    cout<<"十进制2:"<<str<<endl;//      1234

    sprintf(str,"%o",1234);
    cout<<"八进制1:"<<str<<endl;//2322

    sprintf(str,"%#o",1234);
    cout<<"八进制2:"<<str<<endl;//02322

    sprintf(str,"%x",1234);
    cout<<"十六进制1:"<<str<<endl;//4d2

    sprintf(str,"%#x",1234);
    cout<<"十六进制2:"<<str<<endl;//0x4d2

    sprintf(str,"%#X",1234);
    cout<<"十六进制3:"<<str<<endl;//0x4D2

    sprintf(str,"%08X",1234);
    cout<<"十六进制4:"<<str<<endl;//000004D2


    sprintf(str,"%f",3.1415926);
    cout<<str<<endl;//3.141593

    sprintf(str,"%f",30.1415926);
    cout<<str<<endl;//30.141593

    //打印宽度为10,小数点后保留三位
    //宽度不足,默认补0
    sprintf(str,"%10.3f",3.1415926);
    cout<<str<<endl;//     3.142

    sprintf(str,"%010.3f",3.1415926);
    cout<<str<<endl;//000003.142

    sprintf(str,"%.3f",3.1415926);
    cout<<str<<endl;//3.142

    /**
    int i=100;
    sprintf(str,"%.2f",i);
    cout<<str<<endl;
    //注意,注释int i=100前无关代码
    //运行结果为0.00!!!
    sprintf(str,"%.2f",(double)i);
    cout<<str<<endl;//100.00
    */
    return 0;
}


  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值