C++中 sprintf函数的用法


//转载

C++中 sprintf函数的用法

1.常用方式
 sprintf函数的功能与printf函数的功能基本一样,只是它把结果输出到指定的字符串中了,看个例子就明白了:

例:将”test 1 2”写入数组s中

 

#include<stdio.h>
int main(int argc, char *avgv[])
{
    char s[40];
    sprintf(s,"%s%d%c","test",1,'2');
    /*第一个参数就是指向要写入的那个字符串的指针,剩下的就和printf()一样了
    你可以比较一下,这是向屏幕输入*/
    printf("%s%d%c","test",1,'2');
    return 0;
}12345678910

编译:


  g++ sprinftest.cpp -o sprinftest && ./sprinftest


输出结果:


  sprintftest12
  sprintftest12


2.若”%s”等输出符在字符串中

例:补全字符串str的缺省内容

 

#include <iostream>
#include <stdio.h>
#include <cstring>

int main(int argc, char *avgv[])
{
    char str[] = "hel%co wo%sd! sp%stf test%d";
    char buf[strlen(str)];
    sprintf(buf, str, 'l', "rl", "rin", 1);
    std::cout << "str = "<< buf << "\nlen = " <<  strlen(buf) << std::endl;
    return 0;
}123456789101112

编译:


  g++ sprinftest.cpp -o sprinftest && ./sprinftest


输出结果:


  str = hello world! sprintf test1
  len = 27


这种形式也可以将多个字符值或字符串值赋值到字符串str中,有多少个输出符就后面就加多少个参数。
————————————————
版权声明:本文为CSDN博主「wonderomg」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u012406177/article/details/70243062


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM