Com*_* 10 1 c++ string vector char
我试图将a转换std::string为char*(复制而不是转换),因为必须将一些数据传递给相当过时的API.
从表面上看,有很多方法可以做到这一点,但有人建议我这样做是一个看似合理的向量.但是,当我尝试这个时,结果是乱码.代码如下:
const string rawStr("My dog has no nose.");
vector<char> str(rawStr.begin(), rawStr.end());
cout << "\"" << (char*)(&str) << "\"" << endl;
Run Code Online (Sandbox Code Playgroud)
(注意令人不快的C演员 - 使用static_cast不起作用,这可能告诉我一些事情)
当我运行这个时,我得到:
"P/"
Run Code Online (Sandbox Code Playgroud)
显然不对.我看了一下gdb中的向量
(gdb) print str
$1 = std::vector of length 19, capacity 19 = {77 'M', 121 'y', 32 ' ', 100 'd', 111 'o',
103 'g', 32 ' ', 104 'h', 97 'a', 115 's', 32 ' ', 110 'n', 111 'o', 32 ' ', 110 'n',
111 'o', 115 's', 101 'e', 46 '.'}
Run Code Online (Sandbox Code Playgroud)
虽然最后没有空终结符,但这看起来是正确的,这是令人担忧的.vector(sizeof(str))的大小为24,表示字符存储为8位.
我哪里错了?
实例std::vector本身不是一个字符数组 - 它指向一个数组.而不是(char*)(&str)尝试&str[0].
从您的gdb输出判断,您还需要将一个零推到矢量的末尾,然后再将其传递给您的旧API.
首先,std::string不包含空终止作为[ begin(),end()] 所涵盖范围内的元素.其次,向量的地址不是向量数据的第一个元素的地址.为此您需要&str[0]或str.data():
#include <vector>
#include <string>
#include <iostream>
int main()
{
const std::string rawStr("My dog has no nose.");
std::vector<char> str(rawStr.begin(), rawStr.end());
str.push_back('\0');
std::cout << "\"" << &str[0] << "\"" << std::endl;
std::cout << "\"" << str.data() << "\"" << std::endl; // C++11
}
Run Code Online (Sandbox Code Playgroud)