我想使用strtok()将行划分为令牌,但是该函数似乎只是制作第一个令牌,其余的“销毁”。我使用printf()检查发生在哪里,并发现它只是在token= strtok(line,delimit)之后。
这是我的主要read_line和parse_args函数:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PROMPT "$"
#define MAX_LINE 512
void main(){
    char line[MAX_LINE];
    while(read_line(line)){
        execute_line(line);
    }
}

char *read_line(char *line){
    printf("%s ",PROMPT);
    fflush(stdout);
    line=fgets(line,MAX_LINE,stdin);
    return line;
}

int parse_args(char **args, char *line){
    printf("%s", line); //If it reads "Hello how are you?", here it prints properly
    int n=0;
    char* token;
    char delimit[]=" \t\r\n\v\f";
    token=strtok(line,delimit);
    printf("%s", line); //however here it just prints "Hello"
    while(token!=NULL){
        printf("token%i: %s\n",n,token);
        *args=token;
        n++;
        *args++;
        token=strtok(NULL,delimit);
    }
    printf("token%i: %s\n",n,token);
    *args=token;
    return n;
}

int execute_line(char *line){
    char **args;
    parse_args(args,line);
    check_internal(args);
    return 0;
}

最佳答案

strtok用NUL字符替换定界符,以便它可以返回指向仍在原始缓冲区中的令牌的指针。

*args++具有误导性。它的确会递增args,但*是不必要的。

关于c - strtok似乎删除了字符串部分-我使用的对吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40695870/

10-12 12:19
查看更多