简体   繁体   English

在C strtok()中拆分字符串

[英]Splitting strings in C strtok()

I want to split strings received from the terminal input, if they are contained on a buffer. 我想拆分从终端输入接收的字符串(如果它们包含在缓冲区中)。 If they are I want to print them. 如果它们是我要打印的。

#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;
}

My output is the following one: 我的输出是以下内容:

ha he
ha
he

he

Segmentation fault (core dumped)

I suspect your problem is here: 我怀疑您的问题在这里:

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

That second printf will cause undefined behavior (likely a crash) when strtok returns NULL , as it will when there are no more tokens in the string. strtok返回NULL ,第二个printf会导致未定义的行为(可能是崩溃),就像字符串中没有更多的标记时一样。 Just remove that line. 只需删除该行。

Stylistically, I'd use a for loop here: 从风格上讲,我在这里使用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);
    }

The while loop will fail when the token is NULL . 当令牌为NULL时,while循环将失败。 At this time you are trying to print this pointer using your second printf() in the while loop which will lead to undefined behavior. 目前,您正在尝试在while循环中使用第二个printf()打印此指针,这将导致未定义的行为。

Get rid of your second printf() 摆脱第二个printf()

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

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