sprintf基本用法

版权声明:本文为博主原创文章,未经博主允许不得转载。个人网站独立博客:http://wuyunfeng.cn/ https://blog.csdn.net/hurmishine/article/details/69486640

学过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;
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页