sprintf,输出到空间
01 sprintf 格式化字符串
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//1、格式化字符串
void test1()
{
char buff[100] = { 0 };
//printf( "%s", "参军徐赤特");
sprintf(buff, "%s", "参军徐赤特");
printf("%s\n\n", buff);
}
void main() {
test1();
system("pause");
}
02 sprintf 拼接字符串
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//2、拼接字符串
void test2()
{
//栈区指针指向堆区,字符串常量区拷贝到堆区
char* s1 = "辅国将军王仲德";
char* s2 = "建威将军孙处";
//栈区
char s[1024] = { 0 };
memset(s, 0, 1024);
sprintf(s, "%s和%s\n", s1, s2);
printf("%s\n", s);
}
void main() {
test2();
system("pause");
}
03 sprintf 数字转字符串
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//3、数字转字符串
void test3()
{
char s[1024] = { 0 };
memset(s, 0, 1024);
int number = 666;
sprintf(s, "%d\n", number);
printf("%s\n", s);
}
void main() {
test3();
system("pause");
}
04 sprintf 二级指针给指针数组赋值
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//4、指针数组
void test4()
{
//char* pp[10] = {0};//这样也行
//用二级指针指向一级指针数组的头部
char** pp = malloc(sizeof(char*)*10);
for (int i = 0; i < 10; ++i)
{
pp[i] = malloc(64);
//每个pp[i]从0-64字节都初始化
memset(pp[i], 0, 64);
sprintf(pp[i], "%d", i + 1);
}
for (int i = 0; i < 10; ++i)
{
printf("%s,", pp[i]);
printf("%s,", *(pp+i));
}
for (int i = 0; i < 10; ++i)
{
if (pp[i])
{
free(pp[i]);
pp[i] = NULL;
}
}
}
void main() {
test4();
system("pause");
}
05 sprintf 格式化八进制、十六进制
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//5、格式化八进制、十六进制
void test5()
{
char buff[1024] = { 0 };
memset(buff, 0, 1024);
sprintf(buff, "%o", 666);
printf("\n\n%s\n", buff);
sprintf(buff, "%x", 666);
printf("%s\n", buff);
}
void main() {
test5();
system("pause");
}