如何将字符串转换为char *数组 [英] How to convert string into char * array
问题描述
我改变了我的代码,现在编译时出现这些错误:
I have changed my code, now while the compilation these errors occur:
`check.cpp: In function ‘int main()’:`
check.cpp:14:55:error :从'const char **'到'char * const *'的无效转换[-fpermissive]
usr / include / getopt.h:152:12:error:初始化'int getopt(int,char * const *,const char *)'的参数2 [-fpermissive]
int main() {
string text="-f input.gmn -output.jpg";
int argc=text.length();
cout<<"argc: "<<argc<<endl;
char const * argv = text.c_str();
cout<<"argv: "<<argv<<endl;
int c = getopt (argc, &argv, "f:s:o:pw:h:z:t:d:a:b:?");
return 0;
}
推荐答案
$ c> text.c_str()将 std :: string
转换为 const char *
。请参见此处。
You can use text.c_str()
to convert a std::string
into a const char*
. See here.
要详细说明我的答案,有许多方法可以创建所需的数组,但这已在此处中介绍过。 ,此处,此处 a>和此处。一个简单的解决你的问题,不涉及新
/ malloc
或密集使用的STL和 istringstream
/ back_inserter
/ copy
:
To elaborate on my answer, there are many ways to create the array you need, but this is already described here, here, here and here. A simple solution to your problem that does not involve new
/malloc
or intensive uses of the STL and istringstream
/back_inserter
/copy
what not and performs really fast could look like this:
/* variables. */
std::vector< char* > argv;
int i, argc, state;
char c;
/* convert string to char string with automatic garbage collection. */
std::vector< char > tokens(text.begin(), text.end());
tokens.push_back(0);
/* tokenize string with space. */
for (state=0, argc=0, i=0; (c=tokens[i]); i++) {
if (state) {
if (c == ' ') {
tokens[i]=0;
state=0;
}
} else {
if (c != ' ') {
argv.push_back(&tokens[i]);
argc++;
state=1;
}
}
}
/* print argv. */
std::cout << "argc: " << argc << std::endl;
for (i=0; i < argc; i++) {
std::cout << "argv[" << i << "]: " << argv[i] << std::endl;
}
/* call getopt. */
c = getopt(argc, &argv[0], "f:s:o:pw:h:z:t:d:a:b:?");
这只是一个例子,但这种代码的一个优点是可以使用其他字符作为分隔符,而不仅仅是空格,并且您不需要关心释放分配的内存,因为 std :: vector
在函数退出时为您执行此操作。
This is just an example, but one advantage of this kind of code is that you can use other characters as delimiter, not just space, and that you need not care about releasing the allocated memory since std::vector
does this for you on function exit.
这篇关于如何将字符串转换为char *数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!