我有这样声明的255个字符的字符串数组cmd:

char cmd[255];


我使用fgets通过这种方式获取用户输入:

fgets(cmd, 256, stdin);


我有三个单独的数组来存储三个以这种方式声明的令牌(假设用户仅输入最多具有2个空格的字符串):

char arg[20];
char arg2[20];
char arg3[20];


我用strtok在cmd中分割字符串:

char *p = strtok(cmd, " ");

while (p!= NULL) {

// I want to store the tokens p in the arrays here (e.g:
// arg = p is not working
// arg2 = p ...

p = strtok(NULL, " ");
}


以这种方式在指针中分配值不起作用。我可以怎么做吗?

我必须将令牌存储在以null结尾的字符串中

最佳答案

像这样:

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

#define ARG_LEN 20

int main(void){
    char cmd[256];

    if(fgets(cmd, sizeof cmd, stdin)){
        char arg[ARG_LEN+1], arg2[ARG_LEN+1], arg3[ARG_LEN+1];
        char *args[] = { arg, arg2, arg3, NULL };
        char **pp = args;
        const char *delimiter = " \t\n";//Include \n

        for(char *p = strtok(cmd, delimiter); p && *pp; p = strtok(NULL, delimiter)){
            strncpy(*pp, p, ARG_LEN);
            (*pp++)[ARG_LEN] = 0;//Cut it if it is too long
        }
        for(size_t i = 0; args + i < pp; ++i){
            printf("argument #%zu: '%s'\n", i+1, args[i]);
        }
    }
}




sscanf版本。

#include <stdio.h>

//Stringification
#define S_(n) #n
#define S(n) S_(n)

#define FMT "%" S(ARG_LEN) "s"

#define ARG_LEN 20

int main(void){
    char cmd[256];

    if(fgets(cmd, sizeof cmd, stdin)){
        char arg[ARG_LEN+1], arg2[ARG_LEN+1], arg3[ARG_LEN+1];
        char *args[] = { arg, arg2, arg3 };
        int ret_scnf = sscanf(cmd, FMT FMT FMT, arg, arg2, arg3);
        for(int i = 0; i < ret_scnf; ++i){
            printf("argument #%i: '%s'\n", i+1, args[i]);
        }
    }
}

关于c - 使用strtok插入数组并在唯一的以null终止的字符串中存储 token ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43728469/

10-10 21:02
查看更多