strtok_s ignors first characters

Viewed 39

I'm trying to get an input and it to four variable names.

I'm doing a checkup after every strtok_s to see what I got but the first word only counts after 4 characters.

My code:

void zeros()
{
    char buffer[81];
    fgets(buffer, sizeof(buffer), stdin);
    printf("%s\n", buffer);
    char *command = strtok_s(buffer, " \t", &buffer);
    printf_s("the command you selcted is %s\n", command);
    char *Matname = strtok_s(NULL, " \t", &buffer);
    printf_s("the name you selcted is %s\n", Matname);
    char *row = strtok_s(NULL, "  \t", &buffer);
    printf_s("the rowsize you selcted is %s\n", row);
    char *col = strtok_s(NULL, " \t", &buffer);
    printf_s("the colsize you selcted is %s\n", col);
    return 0;
}
1 Answers

The last argument of strtok_s is not correct, it should be a pointer which is used by strtok_s to store its internal state.

Your function should look more like this:

void zeros() // or int zeros() if it's supposed to return int
{
    char buffer[81];
    char *ptr;
    fgets(buffer, sizeof buffer, stdin);
    printf("%s\n", buffer);
    char *command = strtok_s(buffer, " \t", &ptr);
    printf_s("the command you selcted is %s\n", command);
    char *Matname = strtok_s(NULL, " \t", &ptr);
    printf_s("the name you selcted is %s\n", Matname);
    char *row = strtok_s(NULL, "  \t", &ptr);
    printf_s("the rowsize you selcted is %s\n", row);
    char *col = strtok_s(NULL, " \t", &ptr);
    printf_s("the colsize you selcted is %s\n", col);
    // return 0; // if function return type is int
}

Another issue, albeit not the main one, is that the function has void return type and returns an int.

Related