sprintf()函数的用法

xiaoxiao2021-02-28  100

  sprintf()函数用于将格式化的数据写入字符串,它包含在头文件<stdio.h>中,所以用之前需要包含进来,即#include<stdio.h>

  函数原型:int sprintf(char *str,char *format[...,argument,...])

  其中,str是要写入的字符串,format是格式化的字符串。我们所想要的就是将第二个参数中的argument写入str中。

  其实sprintf()是将argument打印到字符串中,而printf()是将argument打印到屏幕上。

  实例:(代码亲测能用)

  ①

   #include <iostream>    #include "stdio.h"    #pragma warning(disable:4996)//这一语句需要加上,否则会报错。当然这不是程序本身的语法错误,而是为了避免溢出,系统的警告。

   using namespace std;    int main()    {  char* who = "I";  char* whom = "you";  char s[40];  sprintf(s, "%s love %s.", who, whom); //产生:"I love you. "  cout << s << endl;//屏幕输出I love you.  getchar();  return 0;    }

  最终输出:I love you.

  ②

   可以在格式串的内部是用“%”来占据一个位置,用后面相应位置的参数(argument)来代替“%”,最终产生想要的字符串。

   #include <iostream>   #include "stdio.h"   #pragma warning (disable:4996)   using namespace std;   int main()   {   char s1[20],s2[20],s3[20];   sprintf(s1, "%d", 123);//产生123,字母d代表十进制   cout << s1 << endl;   sprintf(s2, "123%d", 456);//产生123456   cout << s2 << endl;   sprintf(s3, "123%x", 12);//产生123c,字母x代表十六进制,所以12变为了c   cout << s3 << endl;   getchar();   return 0;   }

  最后屏幕输出:123

                           123456

                            123c

转载请注明原文地址: https://www.6miu.com/read-57249.html

最新回复(0)