我有以下代码片段:

char *buffer2 = malloc(1024*sizeof(char));
    scanf("%s",buffer2);
    char *command = strtok(buffer2," ");

    if (strcmp(command,"INFO") == 0)
    {
        char *file_path = strtok(NULL," ");
        if (file_path != NULL)
         {
            info(file_path);
         }
    }


我的目标是:给出一个类似于“ CMD_NAME ARG1 ARG2”的字符串,以便按照这种格式标记该字符串。到目前为止,我已经编写了上面的代码,可以编译,程序不会崩溃,但是结果是错误的,因为如果我输入字符串“ INFO work / file1.sf”,便会解析该命令正确,但对于file_path,strtok函数返回NULL指针。我已经为这个问题苦苦挣扎了好几个小时,我已经阅读了有关此功能的文档,还搜索了与此主题相关的其他回复,但没有一个令人满意。如果您知道我在做什么错,请帮助我。

最佳答案

给出以下代码:

char *buffer2 = malloc(1024*sizeof(char));
scanf("%s",buffer2);
char *command = strtok(buffer2," ");

if (strcmp(command,"INFO") == 0)
{
    char *file_path = strtok(NULL," ");
    if (file_path != NULL)
     {
        info(file_path);
     }
}


标准将表达式'sizeof(char)'定义为1。
乘以1不会改变其值
并且对传递给malloc()的参数没有影响。

但是,它会使代码混乱,使理解,调试和维护更加困难。

建议删除该表达式。

呼叫scanf()


始终检查返回的值,以确保操作成功。
使用“%s”格式说明符时。
必须使用最大输入字符修饰符,以便用户不能超出输入buffer2
遇到任何“空白”时,“%s”格式说明符将停止输入
调用strtok()只会找到整个输入行。
因为输入将在输入任何空格之前停止
因为space是“空白”字符之一。


建议以下代码:

#define BUFFER_LEN (1024)
char *buffer2 = NULL;
if( NULL == (buffer2 = malloc( BUFFER_LEN ) ) )
{ // then malloc failed
    perror( "malloc for 1024 bytes failed")
    exit( EXIT_FAILURE );
}

// implied else, malloc successful

if( !fgets( buffer2, BUFFER_LEN, stdin ) )
{// then, fgets failed
    perror( "fgets from stdin failed");
    exit( EXIT_FAILURE )''
}

// implied else, fgets successful

char *command = NULL;

if( NULL != (command = strtok(buffer2," \n") ) )
{
    if (strcmp(command,"INFO") == 0)
    {
        char *file_path = NULL;
        if( NULL != (file_path = strtok(NULL," \n") ) )
        {
            info(file_path);
        }
    }
}

关于c - strtok不会返回所有 token ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36184826/

10-12 16:38
查看更多