2013-05-20 63 views
1

我正在编写一个程序,我使用strtok来查找字符串中的每个单词,并在命令行中输入,在我的示例中,我的代码称为命令。 ç所以当我键入:C程序使用strtok查找字符串中的单个词

./command.out "Hi, there" 

我应该得到我的结果:

Arg = "Hi, there" 
Next word "Hi," 
Next word "there" 

到目前为止我的代码将完成打印语句的ARG一部分,但不会用在执行后半部分为了分开有问题的字符串,我的代码目前如下:

#include <stdio.h> 
#include <string.h> 

void main (int argc, char *argv[]) { 
    int i; 

    for(i =1;i< argc; i++) 
    printf("Arg = %s\n", argv[i]); 
    char delims[] = " "; 
    char *word = NULL; 
    word = strtok(argv[i], delims); 

    while(word != NULL) { 
     printf("Next word \"%s\"\n", word); 
     word = strtok(NULL, delims); 
    } 
} 

我在哪里出错了,我该如何解决这个问题?感谢所有帮助

回答

7

你缺少大括号围绕for块:

for(i =1;i< argc; i++) 
{ 
    printf /* ... and so forth */ 
} 
+0

愚蠢的Python语法再次罢工。 – jxh

+0

@ user315052:没有什么,一个半正派的编辑不赶上... –

+0

哈哈,这样一个愚蠢的错误,谢谢你们 – Student

0

你的代码缩进是错误的,这可能会导致您的问题。 'for'语句只影响下一行,printf one,所以变量'i'稍后增加为值'2',然后当您询问argv [i]时,您要求输入argv [2] ],你应该调用argv [1]。

相关问题