2014-12-05 85 views
-1

我想拆分从终端输入收到的字符串,如果它们包含在缓冲区中。如果他们是我想打印它们。拆分字符串在C strtok()

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

char* fich[5]={"ha","he","hi","ho","hu"}; 

int main(){ 

char passaarg[70]; 
const char space[2]= " "; 
char *token; 
int i; 

while(1){ 

    read(STDIN_FILENO, passaarg, 70); 
    for (i = 0; i < 5; i++){ 
     if(strncmp(passaarg, fich[i], 2) == 0){ 
      token = strtok(passaarg, space); 
      while(token != NULL){ 
       printf("%s\n", token); 
       token = strtok(NULL, space); 
       printf("%s\n", token); 
      } 
      break; 
     } 
    } 
} 
return 0; 
} 

我的输出如下一个:提前

ha he 
ha 
he 

he 

Segmentation fault (core dumped) 

谢谢!

+1

你的第二个'printf'最终将尝试打印'NULL'字符串。 – 2014-12-05 15:24:29

回答

2

我怀疑你的问题是在这里:

token = strtok(passaarg, space); 
while(token != NULL){ 
    printf("%s\n", token); 
    token = strtok(NULL, space); 
    printf("%s\n", token); 
} 

这第二printf将导致不确定的行为(有可能是崩溃)时strtok回报NULL,因为它会在那里在字符串中没有更多的标记。只要删除该行。

风格上,我会在这里使用一个for循环:

for(token = strtok(passaarg, space); token != NULL; token = strtok(NULL, space)) { 
    printf("%s\n", token); 
} 
+0

同意,我总是喜欢'strtok()'的for-loop结构。 – JohnH 2014-12-05 17:49:54

0
while(token != NULL){ 
     printf("%s\n", token); 
     token = strtok(NULL, space); 
    } 

当令牌为NULL时,while循环将失败。此时,您正尝试在while循环中使用第二个printf()来打印此指针,这将导致未定义的行为。

摆脱你的第二个printf()