02 13 sprintf 格式化、拼接字符串、数字转字符串、二级指针与指针数组 格式化8、16进制

02 13 sprintf

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");
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值