我的理解是 c_str
将可能以或不以空字符结尾的字符串转换为以空字符结尾的字符串。
这是真的?你能举一些例子吗?
原文由 Amit Singh Tomar 发布,翻译遵循 CC BY-SA 4.0 许可协议
我的理解是 c_str
将可能以或不以空字符结尾的字符串转换为以空字符结尾的字符串。
这是真的?你能举一些例子吗?
原文由 Amit Singh Tomar 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 C/C++ 编程中有两种类型的字符串:C 字符串和标准字符串。使用 <string>
标头,我们可以使用标准字符串。另一方面,C 字符串只是一个普通字符数组。因此,为了将标准字符串转换为 C 字符串,我们使用 c_str()
函数。
例如
// a string to a C-style string conversion//
const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;
输出将是,
Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str
Operation: strlen(cstr1)
The length of C-style string str1 = 17
原文由 Linkon Ruhul 发布,翻译遵循 CC BY-SA 3.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答2.7k 阅读✓ 已解决
c_str
返回一个const char*
指向一个以 null 结尾的字符串(即 C 风格的字符串)。当您想将std::string
的“内容”¹传递给期望使用 C 样式字符串的函数时,它很有用。例如,考虑以下代码:
看到它在行动。
笔记:
¹ 这并不完全正确,因为
std::string
(与 C 字符串不同)可以包含\0
字符。如果是这样,接收c_str()
的返回值的代码将被愚弄认为该字符串比实际短,因为它会将\0
解释为结束细绳。