sprintf函数的使用方法

一、介绍

1、该函数包含在stdio.h的头文件中,因此需要  #include <stdio.h>。
2、sprintf和平时我们常用的printf函数的功能很相似。sprintf函数打印到字符串中(要注意字符串的长度要足够容纳打印的内容,否则会出现内存溢出),而printf函数打印输出到屏幕上。sprintf函数常用于像数组中封装特定的字符串。
3、sprintf函数的格式:
int sprintf( char *buffer, const char *format [, argument,…] );

注意 sprintf函数的第一个参数为字符型指针,因此声明时,数组注意声明称字符型;若声明为其他类型,注意转换。

二、例句

例:

1、

char str[20];   //直接声明为字符串数组

sprintf(str,"%d-%2d-%2d",year,month,day);

2、

unsigned char str[20];   //不是直接声明为字符串数组,要进行转换

sprintf((char*)str,"%d-%2d-%2d",year,month,day);

猜你喜欢

转载自blog.csdn.net/m0_59113542/article/details/125577570