sprint()功能
1.把其他类型的数据转化成字符串
2.字符串连接
#include <windows.h> #include <stdio.h> int main() { /*sprintf 原型:int _cdecl sprintf(char* _Dest,const char* _Format,...) 功能:把格式化的数据写入到_Dest字符串中,返回值:字符串的长度(strlen) //格式化:百分比,精确小数点后几位,二、八、十、十六进制输出,左右对齐,日期时间 */ //格式化数据字符串,通常可以取代 itoa()等函数 char buffer[200];//若改成char* buffer;有问题 char c = '1'; int i = 35; float f = 1.7320534f; //打印地址 sprintf(buffer,"%p",&f);//16进制的;sprintf(buffer,"%d",&f);sprintf(buffer,"%u",&f);//u:unsigned无符号, printf("%s\n",buffer); sprintf(buffer,"%u",&f);//u:unsigned无符号;等于 sprintf(buffer,"%d",&f); //都是十进制的 printf("%s\n",buffer); sprintf( buffer, "%c",c); //输出“1” sprintf( buffer, "%d",i); //输出“35” sprintf( buffer, "%.3f",f); //输出“1.732” //连接字符串,通常可以取代 strcat(),strcat char* who="I",*whom="CSDN"; sprintf(buffer,"%s love %s.\n",who,whom); char s[] = "computer"; int j=0; j = sprintf( buffer, " String: %s\n", s ); j += sprintf( buffer + j, " Character: %c\n", c ); j += sprintf( buffer + j, " Integer: %d\n", i ); j += sprintf( buffer + j, " Real: %f\n", f ); // Note: sprintf is deprecated; consider using sprintf_s instead printf( "Output:\n%s\ncharacter count = %d\n", buffer, j ); //Unicode版本的swprintf(),wprintf()。注意字符串前面的L wchar_t buf[100]; int len = swprintf( buf, L"%s", L"Hello world" ); wprintf( L"wrote %d characters: %s\n", len,buf ); //输出 11 Hello World len = swprintf( buf,L"%s", L"Hello\xffff world" ); // swprintf fails because string contains WEOF (\xffff) wprintf( L"wrote %d characters: %s\n", len,buf );// 输出 -1 Hello? system("pause"); //sprintf_s()是sprintf()的安全版本,通过指定缓冲区长度来避免sprintf()存在的溢出风险 return 0; }