一些关于字符串处理的函数(一)

// sscanf的用法 
#include <iostream>
#include <cstdio> // sscanf的头文件 
#include <string> // 将string类型转化为字符指针类型的头文件(const char* c_str() const;) 
#include <cstdlib> // atof/atoi 函数的头文件 


// c_str()函数没有参数,返回一个指向以null结尾的字符数组的常量指针(const char*)。
// 该指针指向string对象中存储的字符数据,并以null字符('\0')结尾。
// 注意,c_str()函数返回的字符指针是一个常量指针,意味着不能通过该指针修改字符串内容。
// 这是因为string类保证了字符串的不可变性,通过c_str()函数返回的指针只能用于读取字符串内容,
// 不能用于修改。


// int sscanf(const char *str, const char *format, ...);
// str是要读取数据的字符串,format是格式控制字符串,用于指定要读取的数据的格式,
// ...是需要读取的数据的地址。
using namespace std;
int main () {
	// 读取整数
	int num1, num2;
	string s1 = "4 is a student of school 3";
	//sscanf(s1.c_str(), "%d is a student of school %d", &num1, &num2); // 匹配时会自动跳过多余的空格
	sscanf(s1.c_str(), "%d    is  a  student  of  school   %d", &num1, &num2); 
	cout << "num1 = " << num1 << " num2 = " << num2 << endl;
	// 读取浮点数
	double  d1, d2;
	string s2 = "3.2 is less than 9.7 ...";
	sscanf(s2.c_str(), "%lf is less than %lf ...", &d1, &d2);
	cout << "d1 = " << d1 << " d2 = " << d2 << endl;
	// 读取字符串, 字符串不能含有空格 
	//char ch[20];// 为ch分配足够的空间
	char* ch = new char; 
	string s3 = "the classmate is LiMing's friend";
	sscanf(s3.c_str(), "the classmate is %s friend", ch);
	cout << "ch = " << ch << endl;
	// char* 转 string
	char c[20] = "abcde";
	// 法一 
	string s(c);
	cout << s << endl;
	// 法二 
	string ss;
	ss = c;
	cout << ss << endl;
	// 字符数组转数值
	char testch1[10] = "134";
	cout << atoi(testch1) << endl; // 转整数 
	char testch2[10] = "1.97";
	cout << atof(testch2) << endl; // 转浮点数 
	return 0;
} 
#include <iostream>
#include <string>
using namespace std;
int main () {
	//string s = "I am a college student?";
	string s1;
	string s2;
	// 遇到换行自动结束,中间可以出现空格 
	getline(cin, s1);
	getline(cin, s2);
	cout << "s1 = " << s1 << endl;
	cout << "s2 = " << s2 << endl;
	// 另外,std::getline函数还可以接收一个可选的第三个参数,用于指定分隔符。
	// 默认情况下,分隔符是换行符('\n'),但你可以指定其他字符作为分隔符。例如:
    // getline(cin, line, ',');
    //上述代码会从输入流中读取一行字符串,直到遇到逗号(',')为止,并将结果存储在line变量中。
    // cin.get()获取单个字符 
	char ch;
    ch = cin.get();
    cout << "You entered: " << ch << endl;
	return 0;
} 

未完待续...

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值