在C strtok()中拆分字符串

时间:2014-12-05 15:19:07

标签: c string split 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)

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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

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

摆脱你的第二个printf()