C++ 字符(char)转字符串(string)

本文详细介绍了在C++中将char类型转换为string的三种常见方法:通过append()函数、stringstream和string构造函数,并提供了实例代码。同时提到了使用to_string()的误区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

char转string

误区

无法使用to_string()方法

char c = 'c';
cout << to_string(c) == "c" ? true : false << endl;

这样是错误的to_string是将char字符的ASCII码值转换成了字符串

方法一

定义一个空string,调用append()方法

char c = 'c';
string s = "";
s.append(1, c);
cout << s == "c" ? true : false << endl;

方法二

使用stringstream,注意添加相应头文件

#include <sstream>
stringstream stream;
char c = 'c';
stream << c;
cout << stream.str() == "c" ? true : false;

方法三

使用string构造函数

char c = 'c';
string s(1, c);
cout << s == "c" ? true : false << endl;

相关阅读

C++字符串与数字相互转换

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值