cstring头文件中包含的函数

cstring中包含许多字符数组的函数:

  1. strlen()函数:strlen函数可以得到字符数组中第一个\0前的字符的个数

  2. strcmp()函数: strcmp函数返回两个字符串大小的比较结果,比较原则是按字典序
    在这里插入图片描述

  3. strcpy()函数: strcpy函数可以把一个字符串复制给另一个字符串
    在这里插入图片描述

  4. strcat()函数: strcat()可以把一个字符串接到另一个字符串后面
    在这里插入图片描述

sscanf与sprintf用法:

假设定义了一个字符数组str[100],如下:

sscanf(str, "%d", &n);
sprintf(str,"%d",n);

(1) 上面sscanf写法的作用是把字符数组str中的内容以"%d"的格式写到n中(还是从左至右),示例如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	char str[15] = "123";
	int n;
	sscanf_s(str, "%d", &n);
	printf("%d", n);
	system("pause");
	return 0;
}

输出结果: 123

(2) 而sprintf写法的作用是把n以"%d"的格式写到str字符数组中(还是从右至左),示例如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	char str[15];
	int n=123;
	sprintf(str, "%d", n);
	puts(str);
	system("pause");
	return 0;
}

输出结果: 123

上面只是一些简单的应用,事实上,还可以像使用scanf printf那样进行复杂的格式输入和输出。例如下面的代码使用sscanf将字符数组 str 中的内容按""%d:%1f,%s"的格式写到int型变量n、double型变量db、char 型数组str2中。
示例代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	int n;
	double db;
	char str1[100] = "12:3.14,hello", str2[100];
	sscanf_s(str1, "%d:%lf,%s", &n, &db, str2);
	printf("%d:%lf,%s", n, db, str2);
	system("pause");
	return 0;
}

sprintf函数类似

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值