c++如何输出std::string类型
时间: 2023-12-13 14:05:50 浏览: 36
使用cout输出std::string类型的方法与输出其他基本数据类型相同:
```
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World!";
std::cout << s << std::endl;
return 0;
}
```
输出:
```
Hello, World!
```
相关问题
c++ std::basic_string如何转换为std::string
在C++中,可以使用`std::string`的构造函数将`std::basic_string`转换为`std::string`。`std::basic_string`是`std::string`的基类,因此可以直接进行类型转换。下面是一个示例代码[^1]:
```cpp
#include <iostream>
#include <string>
int main() {
std::basic_string<char> basicStr = "Hello, world!";
std::string str(basicStr); // 将 std::basic_string 转换为 std::string
std::cout << "std::string: " << str << std::endl;
return 0;
}
```
输出结果为:
```
std::string: Hello, world!
```
在上面的示例中,我们首先创建了一个`std::basic_string<char>`类型的对象`basicStr`,并将其初始化为字符串"Hello, world!"。然后,我们使用`std::string`的构造函数将`basicStr`转换为`std::string`类型的对象`str`。最后,我们输出了`str`的值,可以看到成功将`std::basic_string`转换为了`std::string`。
C++ std::string赋值
C++中的std::string是一个字符串类,用于存储和操作字符串。赋值操作是将一个字符串的值赋给另一个字符串。
std::string的赋值操作有多种方式,下面是几种常见的方式:
1. 使用赋值运算符(=):可以将一个字符串直接赋给另一个字符串,例如:
```
std::string str1 = "Hello";
std::string str2 = str1;
```
2. 使用assign()函数:可以将一个字符串赋给另一个字符串,例如:
```
std::string str1 = "Hello";
std::string str2;
str2.assign(str1);
```
3. 使用字符串字面值直接赋值:可以将一个字符串字面值直接赋给一个std::string对象,例如:
```
std::string str = "Hello";
```
4. 使用c_str()函数:可以将一个C风格的字符串(以null结尾的字符数组)赋给一个std::string对象,例如:
```
const char* cstr = "Hello";
std::string str = cstr;
```
5. 使用substr()函数:可以将一个std::string对象的子串赋给另一个std::string对象,例如:
```
std::string str1 = "Hello, world!";
std::string str2 = str1.substr(0, 5); // 将str1的前5个字符赋给str2
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)