繁体   English   中英

在C strtok()中拆分字符串

[英]Splitting strings in 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)

我怀疑您的问题在这里:

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

strtok返回NULL ,第二个printf会导致未定义的行为(可能是崩溃),就像字符串中没有更多的标记时一样。 只需删除该行。

从风格上讲,我在这里使用for循环:

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

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

摆脱第二个printf()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM