【发布时间】:2013-10-29 05:38:57
【问题描述】:
我正在尝试将字符串向量转换为 c++ 中的 char 数组。
更具体地说,我正在尝试使用以下命令拆分 shell 命令,例如“ls –latr”:
istringstream f(x);
while (getline(f, x, ' '))
{
strings.push_back(x);
}
我相信这会给我strings[0] == "ls" 和strings[1]==" -latr"。
我正在尝试执行以下操作:
execvp(strings[0], strings);
但是,我得到了这个错误:
错误:无法将参数“1”转换为“std::basic_string, std::allocator >”为“const char*”到“int execvp(const char*, char* const*)”
因此,我试图弄清楚如何将字符串转换为 char 数组。
【问题讨论】:
-
将
.c_str()添加到strings[0]的末尾;不过,您仍然需要为第二个参数构建另一个指针向量。 -
假设字符串是
std::vector<std::string>,使用strings[0].c_str()。第二个参数需要一个指针数组,所以更复杂。 -
不用getline,你可以简单地说
while (f >> x) { strings.push_back(x); }。
标签: c++