我不是最好的指针,所以也许你可以看到我做错了什么。小strtok()乐趣
比方说,我有一个像这样的初始化数组:
char *arrayOfCommands[]={"ls -l", "wc -l"};
我的目标是获得一个数组称为的char * currentCommand了这阵,着眼于arrayOfCommands的和特定细胞的将命令分隔为空格。
我的最终目标将是对每个循环新currentCommand阵列,每个看起来像这样:
First Loop:
currentCommand = [ls][-l]
First Loop:
currentCommand = [wc][-l]
这里是我的代码至今:
for (i = 0; i < 2; ++i) {
char str[] = arrayOfCommands[i];
char * currentCommand;
printf ("Splitting string \"%s\" into tokens:\n",str);
currentCommand = strtok (str, " ");
while (currentCommand != NULL){
printf ("%s\n",currentCommand);
currentCommand = strtok (NULL, " ");
}
.
.
.
//Use the currentCommand array (and be done with it)
//Return to top
}
任何帮助将非常感谢! :)
UPDATE:
for (i = 0; i < commands; ++i) {
char str[2];
strncpy(str, arrayOfCommands[i], 2);
char *currentCommand[10];
printf ("Splitting string \"%s\" into tokens:\n",str);
currentCommand = strtok (str, DELIM);
while (currentCommand != NULL){
printf ("%s\n",currentCommand);
currentCommand = strtok (NULL, DELIM);
}
}
我收到此错误:在分配**不兼容的类型**
它讲的是 “海峡” 我传递的strtok功能。
你确定'strtok()'是最好的选择吗?你有没有考虑过使用'strcspn()'或'strpbrk()'或类似的东西? 'strtok()'是一个危险的函数。如果你在库函数中使用它,你必须证明你这么做是因为使用它会给任何在使用'strtok()'时调用你的函数的人造成严重破坏。而且你还必须小心,不要因为同样的原因调用任何使用'strtok()'的函数。一般来说,除非有一位老师将你的双手握在火焰中并强迫你将它们留在那里,否则请避开'strtok()'寻找'strtok_r()'。 –
什么'char str [] = arrayOfCommands [i];'是什么意思? –
你似乎在几个地方混合了字符串,char数组和指针数组。也许作为第一步,您可以编写一些只需要一个命令字符串并将其解析为一个令牌数组的东西。做一个函数,现在你可以调用'arrayOfCommands []'中的每个项目。第二个想法是,第一步是在尝试构建一组令牌之前,在单独的行上打印每个令牌。 –