为什么 strtok() 在我的 C 程序中无法正常工作?

问题描述 投票:0回答:2

我正在尝试开发一个小型控制台程序,将字符串分解为单独的单词(即标记)。大部分程序都可以运行,但我在 strtok() 函数方面遇到问题。我已经查看了显示的代码 strtok() 如何将字符串拆分为 C 中的标记? 并在某种程度上基于我自己的代码。我的问题在于我的 makeWordList() 函数,如下所示。

// Assumes a multi-word string was entered.
void makeWordList(char inString[], unsigned int wordCount, char * wordList[])    // Separate out words.
{
   unsigned int index = 0;
   const char * delimiter = " ";
   char * word;

   word = strtok(inString, delimiter);             // Get first word.

   while ((word != NULL) && (index < wordCount))
   {
      wordList[index++] = word;                    // Add word to list.
      word = strtok(inString, delimiter);          // Get next word.
   }  // end while()
}

在我的例子中,strtok() 函数似乎没有沿着(源)输入字符串 inString 移动。当程序运行时,它会产生以下输出

./ex8_4
Enter string to be processed:
three word string
You entered |three word string|

There are 3 words in the string.

There are 15 letters in the string.

The word list is as follows.
three
three
three

从上面显示的输出中可以很容易地看出,strtok() 成功读取了第一个标记(并根据 codeblocks Watches 面板以“”终止),但没有读取 inString 中的后续标记。 由于我使用 strtok() 的方式与上面链接的页面上的代码中显示的方式非常相似,有人可以解释一下我无法理解的是什么吗?

c strtok
2个回答
1
投票

问题是您在循环的每次迭代中使用相同的字符串指针 (inString) 调用 strtok()。这意味着 strtok() 只会从第一个标记的末尾开始查找下一个标记。在您的情况下,第一个标记是“三”,因此 strtok() 只会找到从“三”末尾开始的下一个标记。这就是为什么你的程序输出是“三三三”。

要解决此问题,您需要在循环的每次迭代中向 strtok() 传递不同的字符串指针。您可以通过在第一次迭代中使用 NULL 指针作为字符串指针,然后在后续迭代中使用当前单词指针来实现此目的。

    // Assumes a multi-word string was entered.
void makeWordList(char inString[], unsigned int wordCount, char * wordList[])    // Separate out words.
{
   unsigned int index = 0;
   const char * delimiter = " ";
   char * word;

   word = strtok(inString, delimiter);             // Get first word.

   while ((word != NULL) && (index < wordCount))
   {
      wordList[index++] = word;                    // Add word to list.

      // Get next word.
      word = strtok(NULL, delimiter);
   }  // end while()
}

0
投票

在这个 while 循环中

   while ((word != NULL) && (index < wordCount))
   {
      wordList[index++] = word;                    // Add word to list.
      word = strtok(inString, delimiter);          // Get next word.
   }  

更改此声明

  word = strtok(inString, delimiter);          // Get next word.

  word = strtok(NULL, delimiter);          // Get next word.
© www.soinside.com 2019 - 2024. All rights reserved.