سؤال

I am trying to parse a char * array into tokens and I am researching strtok. However whenever I run my code, it doesn't return anything into my temporary value and I was wondering what I was doing wrong

int length;
int i = 0;
int tokenCounter = 0;
int commandCounter = -1;
char *tempToken;

char tempInput[MAX_LINE];

length = read(STDIN_FILENO, tempInput, MAX_LINE);

commandCounter = -1;

if (length < 0)
{
    perror ("There was an error reading the command");
}
else if (length == 0)
{
    exit (0);
}
else
{
    for (i = 0; i < length; ++i)
    {
        if (tempInput[i] == "\n" || tempInput[i] == ' ' || tempInput == "\t")
        {
            /*
            if (commandCounter != -1)
            {
                pTokens[tokenCounter] = &tempInput[commandCounter];
                ++tokenCounter;
            }

            tempInput [i] = '\0';
            commandCounter = -1;
            */
        }
        else
        {
            tempToken = strtok (tempInput, " \n");

            while (tempToken != NULL)
            {
              strcpy(pTokens[tokenCounter], tempToken);
              tempToken = strtok (tempInput, " \n");
            }
            ++tokenCounter;
        }
    }
}
pTokens[tokenCounter] = NULL;
هل كانت مفيدة؟

المحلول

tempToken = strtok (tempInput, " \n");

Other than the first time NULL pointer has to be passed to strtok, I mean inside the while loop, only NULL has to be passed instead of the string.

tempToken = strtok (NULL, " \n");

نصائح أخرى

the standard to use strtok() is fisrt use input then NULL as parameter. i.e. first time

strtok(input, delimeter)

after that for subsequent breaking of same input string use,

strtok(NULL,delimiter)

strtok() will take the previous input string.
there are many questions discussing about strtok() in stackoverflow itself. go through it to get more information.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top