有没有一种简单的方法可以将std :: string转换为std :: vector我想允许用户输入 任何长度的字符串,然后都有一个动态char数组(向量)。
#include<iostream>
#include<vector>
#include<string>
int main() {
std::vector<char> word;
std::string strWord;
std::getline(std::cin, strWord);
//What comes next?
}
我尝试过的不起作用的一件事是:
strcpy(word, strWord);
我收到错误消息,不存在从“ std :: string”到“ const char *”的适当转换。
那么,既然“单词”是指向char数组的指针,我该如何添加字符串?
答案 0 :(得分:7)
您可以通过std::vector::insert()
将字符串中的字符插入向量。
word.insert(word.end(), strWord.begin(), strWord.end());
要进行转换,使用std::vector
的{{3}}(需要迭代器从中复制数据)也很有用。
word = std::vector(strWord.begin(), strWord.end());