将字符串向量转换为c ++中的char数组 [英] Convert string vector to char array in c++
问题描述
我试图将字符串向量转换为c ++中的字符数组。
更多特别的是,我想要做的是分割一个shell命令ls -latr使用: istringstream f(x);
while(getline(f,x,''))
{
strings.push_back(x);
}
我相信会给我 strings [0] ==ls
和 strings [1] ==-latr
。
我试着做以下:
execvp(strings [0],strings);
但是,我收到此错误:
< >
错误:不能将'std :: basic_string,std :: allocator>'转换为'const char *'为参数'1'到'int execvp(const char *,char * const *)'
因此,我想弄清楚如何将字符串转换为字符数组。
阅读手册显示 execvp
提供了一个指向空字符串的指针数组。所以你需要创建这样的数组。这里有一种方法:
std :: vector< char *> argv(strings.size()+ 1); //一个额外的空值
for(std :: size_t i = 0; i!= strings.size(); ++ i)
{
argv [i ] =& strings [i] [0];
}
execvp(argv [0],argv.data());
I'm trying to convert a string vector to a char array in c++.
More specifically what I'm trying to do is to split a shell command like "ls –latr" by using this:
istringstream f(x);
while (getline(f, x, ' '))
{
strings.push_back(x);
}
I believe that will give me strings[0] == "ls"
and strings[1]==" -latr"
.
I'm trying then to do the following:
execvp(strings[0], strings);
however, I get this error:
error: cannot convert ‘std::basic_string, std::allocator >’ to ‘const char*’ for argument ‘1’ to ‘int execvp(const char*, char* const*)’
Therefore, I'm trying to figure out how I can convert the strings to a char array.
Reading the manual reveals that "execvp
provides an array of pointers to null-terminated strings". So you need to create such an array. Here's one way:
std::vector<char *> argv(strings.size() + 1); // one extra for the null
for (std::size_t i = 0; i != strings.size(); ++i)
{
argv[i] = &strings[i][0];
}
execvp(argv[0], argv.data());
这篇关于将字符串向量转换为c ++中的char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!