我已经更改了我的代码,现在在编译时出现这些错误:
`check.cpp: In function ‘int main()’:`
check.cpp:14:55: 错误:从‘const char**’到‘char* const*’的无效转换[-fpermissive]
/usr/include/getopt.h:152:12: 错误:正在初始化“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;
}
最佳答案
您可以使用 text.c_str()
将 std::string
转换为 const char*
。参见 here .
为了详细说明我的回答,有很多方法可以创建您需要的数组,但这已经被描述了here , here , here和 here .一个简单的解决方案,不涉及 new
/malloc
或大量使用 STL 和 istringstream
/back_inserter
/copy
什么不是并且执行得非常快可能看起来像这样:
/* 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
在函数退出时为您执行此操作。
关于c++ - 如何将字符串转换成char *数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10498744/