c++将字符转换为string
时间: 2023-12-07 17:38:35 浏览: 60
以下是两种C++将字符转换为string的方法:
1.使用strcpy_s()和string构造函数
```c++
char ch[20] = "hello";string str(ch); //使用string构造函数将字符数组转换为string
cout << str << endl; //输出:hello
```
2.使用string的下标运算符[]
```c++
char ch = 'X';
string s = "a"; //初始化一个包含单个字符的string
s[0] = ch; //将需要的字符替换进string对象
cout << s << endl; //输出:X
```
相关问题
c++将数字转换为string
你可以使用 C++ 标准库中的 `to_string` 函数将数字转换为字符串。示例如下:
```cpp
#include <iostream>
#include <string>
int main() {
int num = 12345;
std::string str = std::to_string(num);
std::cout << "The number " << num << " in string format is: " << str << std::endl;
return 0;
}
```
输出结果为:
```
The number 12345 in string format is: 12345
```
你也可以使用 `stringstream` 类来实现相同的功能,示例如下:
```cpp
#include <iostream>
#include <sstream>
int main() {
int num = 12345;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << "The number " << num << " in string format is: " << str << std::endl;
return 0;
}
```
输出结果也是:
```
The number 12345 in string format is: 12345
```
C++ 将字符转换为数字
在 C++ 中,可以使用 `std::stoi()` 函数将字符串转换为整数。例如:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
```
输出结果为:
```
123
```
如果要将单个字符转换为数字,可以先将其转换为字符串,再用 `std::stoi()` 转换为数字。例如:
```cpp
#include <iostream>
#include <string>
int main() {
char c = '5';
std::string str(1, c);
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
```
输出结果为:
```
5
```