简体   繁体   中英

C++ strtok function

char ParseCmd(char *buf,int len)
{
     char *p;
     p = strtok(buf," ");
     return *p;
}

Why does this function only return first symbol in a whole buffer? If I set buffer to a "fsa rew qwe" it returns only "f" instead of the expected "fsa".

"mˣ*" - that is now im getting. why ?

char dum = *InstList->Lines->GetText(); LoadLibrary("SyntaxP.dll"); char *dum1 = ParseCmd(&dum,32); InstList->Lines->Add(dum1);

因为您的返回类型是char ,它代表一个字符,并且您取消引用了strtok()返回的指针。

Because you are returning a char value, which means only the first character of the string pointed by pointer p .You should return a char * from your function.

Your function should have the prototype:

char* ParseCmd(char *buf,int len);
^^^^^

Online Demo :

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

char* ParseCmd(char *buf,int len)
{
     char *p;
     p = strtok(buf," ");
     char *ptr = (char *)malloc(strlen(p)+1);
     strncpy(ptr,p,strlen(p));
     return ptr;
}

int main()
{
    char array[]="fsa rew qwe";
    char* ret = ParseCmd(array,11);
    printf("[%s]",ret);

    /*If You Forget this,You cause a Memory Leak*/    
    free(ret);

    return 0;
}

Output:

[fsa]

Disclaimer: I have not really used any C++ in the code because since You are using strtok and char * instead of string I believe the Q is more C than C++ .

Like any C-style string, p is actually a character array. If you dereference it, you get a character. Have your ParseCmd return p instead of return *p .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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