String tokenizing in Visual Studio C++

135 Views Asked by At

I have been trying to use the strtok function but the function breaks the code every time.

Here is a code part :

if (!strcmp(strtok_s(buf1, " ",NULL), ".model")){
        strcpy_s(buf2, strtok_s(NULL, " ",NULL));
        charPtr1 = strtok_s(NULL, " ",NULL);
        if (!strcmp(charPtr1, "PNP"))
            TtypeBuf = PNP;
        else if (!strcmp(charPtr1, "NPN"))
            TtypeBuf = NPN;
        else if (!strcmp(charPtr1, "NMOS"))
            TtypeBuf = NMOS;
        else if (!strcmp(charPtr1, "PMOS"))
            TtypeBuf = PMOS;

I cannot get the hold of the strtok_s function with one addtitonal input parameter known as context in the function defenition.I just need to get the tokens right. Any help would be appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

strtok_s's context parameter stores data about the current state of the parsing. What it does and how it works, you don't really need to care, but if I remember correctly it's just a pointer to the first character after the last delimiter. All you need to do is provide a char pointer.

char * contextp;
if (!strcmp(strtok_s(buf1, " ", &contextp), ".model")){
        strcpy_s(buf2, strtok_s(NULL, " ", &contextp));
        charPtr1 = strtok_s(NULL, " ", &contextp);
        if (!strcmp(charPtr1, "PNP"))
            TtypeBuf = PNP;
        else if (!strcmp(charPtr1, "NPN"))
            TtypeBuf = NPN;
        else if (!strcmp(charPtr1, "NMOS"))
            TtypeBuf = NMOS;
        else if (!strcmp(charPtr1, "PMOS"))
            TtypeBuf = PMOS;

This can be with strings and stream operators as

std::stringstream in (buf1);
std::string token;

if (stream >> token)
{
    if (token == ".mode1")
    {
        if (stream >> buf2 >> token) // buf2 should become a string as well.
        {
            if (token == "PNP")
                TtypeBuf = PNP;
            else if (token == "NPN")
                TtypeBuf = NPN;
            else if (token == "NMOS")
                TtypeBuf = NMOS;
            else if (token == "PMOS")
                TtypeBuf = PMOS;
        }
    }
}