使用strtok吐出数组并使用唯一的空终止字符串存储标记

我有一个字符串数组cmd,容量为255 chars这样声明:

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结尾的字符串中

回答(3)

2 years ago

像这样:

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

2 years ago

以下可能是有效的 .

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

int main()
{
    char cmd[255] = "";
    char arg[20]  = "" ;
    char arg2[20] = "";
    char arg3[20] = "";
    char *p;

    fgets(cmd, 255, stdin );

    p = strtok(cmd, " ");
    if ( p != NULL ) {
        strcpy( arg, p );
        p = strtok(NULL, " ");
        if ( p != NULL ) {
            strcpy( arg2, p );
            p = strtok(NULL, "");
            if ( p != NULL ) {
                strcpy( arg3, p );
            }
        }
    }


    printf(" arg=%s\n arg2=%s\n arg3=%s\n", arg, arg2, arg3);

    return 0;
}

2 years ago

建议:声明argv如下

char argv[3][20];

通过这样做,它将简化如下代码:

int
main(void)
{
   char cmd[255];
   char argv[3][20];
   char *token;
   char *tstr = " ";

   fgets( cmd, sizeof cmd, stdin );

   token = strtok( cmd, tstr );
   int i = 0;

   while( token != NULL )
   {
        strcpy( argv[i], token);
        printf( "%s\n", argv[i] );
        token = strtok( NULL, tstr ); 
        i++;
   }

   return 0;
}