strok没有正确标记单词

时间:2020-09-25 22:17:36

标签: c token

我正在尝试将单独的单词标记化并将其存储到数组中,但是由于某种原因,第一个单词存储在索引0中,而其余单词未标记化,而是全部存储在索引1中。 我有以下代码。...

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

int main(int argc, char const *argv[])
{
   
    char input[300];

    while (1)
    {
       
        printf ("\nEnter input to check or q to quit\n");
        fgets(input, 300, stdin);

        for (int j = 0; j < 300; j++)
        {
            input[j] = tolower(input[j]);
        }

        /* remove the newline character from the input */
        int i = 0;
        while (input[i] != '\n' && input[i] != '\0')
        {
            i++;
        }
        input[i] = '\0';


        /* check if user enter q or Q to quit program */
        if ( (strcmp (input, "q") == 0) || (strcmp (input, "Q") == 0) )
            break;

        //printf ("%s\n", input);
        /*Start tokenizing the input into words separated by space
        *The tokenized words are added to an array of words*/

        char delim[] = " ";
        char *ptr = strtok(input, delim);
        int j = 0 ;

        
        // allocate our array
        char *wordList[15];
        for (i = 0 ; i < 16; i++)
        {
            wordList[i] = (char *) malloc(sizeof(char) * 300);
        }

        while (ptr != NULL)
        {
            strcpy(wordList[j], ptr);
            printf ("%s\n", wordList[j]);
            ptr = strtok(NULL, delim);
            j++;
        }
        printf ("%s\n", wordList[1]);
    }

    printf ("\nGoodbye\n");

    return 0;
}

预期产量

hello
there 
sir

我得到的输出

hello 
there sir

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

此循环

        // allocate our array
        char *wordList[15];
        for (i = 0 ; i < 16; i++)
        {
            wordList[i] = (char *) malloc(sizeof(char) * 300);
        }

不好,因为它正在写入wordList[15],而只有wordList[0]wordList[14]可用。
delim可能会放在wordList之后,并且写入超出范围的wordList[15]可能会破坏delim的内容。

增加元素数量

        // allocate our array
        char *wordList[16];
        for (i = 0 ; i < 16; i++)
        {
            wordList[i] = (char *) malloc(sizeof(char) * 300);
        }

或者减少迭代次数。

        // allocate our array
        char *wordList[15];
        for (i = 0 ; i < 15; i++)
        {
            wordList[i] = (char *) malloc(sizeof(char) * 300);
        }