gpt4 book ai didi

c++ - C/C++ 指针和数组帮助

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:32 25 4
gpt4 key购买 nike

我有以下 C++ 代码,但我似乎无法让它工作。我想要做的是从命令行读取大量条目,用 ('|') 竖线字符分隔,然后用空格分隔结果字符串。

eg. 

mkdir C:/unixcode/shells|cd D:/margins/code | pwd| finger kobojunkie | last -l kobojunkie

但到目前为止,我收到错误,一些关于声明指针大小的错误:

Initializer fails to determine the size of argv2 cannot convert char** to char* for argument 1 to char strtok(char*, const char*)

int main(int argc, char *argv[])
{
char * pch;
pch = strtok (argv,"|");
//parse the contents of the generated arrays
while (pch != NULL)
{
printf ("%s\n",pch);
char * argv2[] = pch;
char * subpch = strtok(argv2," ");

while (subpch !=NULL)
{
printf ("%s\n",subpch);
subpch = strtok (NULL, " ");
}
pch = strtok (NULL, " ");
}
return 0;
}

最佳答案

argv 的类型是char**,而不是char*,因此您不能将它传递给strtok。请改用 argv[ 1 ],但首先检查 argc >= 2。

或者,因为这是打了c++标签的,所以用STL来分割字符串,eg

void split( const std::string& s, char delim, std::vector<std::string>& elems )
{
std::stringstream ss( s );
std::string item;
while( std::getline( ss, item, delim ) )
if( !item.empty() )
elems.push_back( item );
}

int main( int argc, char *argv[] )
{
if( argc == 2 )
{
std::vector< std::string > elements;
split( argv[ 1 ], '|', elements );
//elements now contains all items..
}
}

关于c++ - C/C++ 指针和数组帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com