如何把char转换成string
时间: 2023-09-26 17:13:59 浏览: 39
你可以使用C++的string类的构造函数将char类型的字符数组转换为string类型的字符串。例如,假设你有一个char类型的字符数组,名为charArray,可以使用如下代码将其转换为string类型的字符串:
```
char charArray[] = {'h', 'e', 'l', 'l', 'o'};
string str(charArray);
```
这将创建一个名为str的字符串对象,其值为"hello"。
相关问题
把char转换成string
可以使用字符串流 stringstream 来将 char 类型转换为 string 类型。以下是示例代码:
```cpp
#include <iostream>
#include <string>
#include <sstream>
int main() {
char c = 'a';
std::stringstream ss;
std::string str;
ss << c;
ss >> str;
std::cout << str << std::endl;
return 0;
}
```
输出结果为:
```
a
```
c++如何把char转换成string
你可以使用C++的string类的构造函数将char类型的字符数组转换为string类型的字符串。例如,假设你有一个char类型的字符数组,名为charArray,可以使用如下代码将其转换为string类型的字符串:
```
char charArray[] = {'h', 'e', 'l', 'l', 'o'};
string str(charArray);
```
这将创建一个名为str的字符串对象,其值为"hello"。
如果你只有一个单独的char类型的字符,你可以使用string类的push_back()函数将其添加到一个空字符串中。例如,以下代码将字符'c'转换为一个字符串:
```
char c = 'c';
string str;
str.push_back(c);
```
这将创建一个名为str的字符串对象,其值为"c"。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)