strtok()C-Strings to Array

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

目前正在学习C,将c-string标记传递给数组有些麻烦。行通过标准输入进入,strtok用于分割行,我想将每个行正确地放入数组中。退出输入流需要EOF检查。这就是我所拥有的,设置它以便将令牌打印回给我(这些令牌将在不同的代码段中转换为ASCII,只是试图让这部分首先工作)。

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

int main()
{
  char string[1024]; //Initialize a char array of 1024 (input limit)

  char *token;
  char *token_arr[1024]; //array to store tokens.
  char *out; //used
  int count = 0;

  while(fgets(string, 1023, stdin) != NULL) //Read lines from standard input until EOF is detected.
  {
    if (count == 0)
      token = strtok(string, " \n"); //If first loop, Get the first token of current input

    while (token != NULL) //read tokens into the array and increment the counter until all tokens are stored
    {
      token_arr[count] = token;
      count++;
      token = strtok(NULL, " \n");
    }
  }

  for (int i = 0; i < count; i++)
    printf("%s\n", token_arr[i]);
  return 0;
}

这对我来说似乎是合适的逻辑,但后来我还在学习。在用ctrl-D发送EOF信号之前,问题似乎是在多行中进行流式传输。

例如,给定输入:

this line will be fine

程序返回:

this line will be fine

但如果给出:

none of this

is going to work

它返回:

is going to work

ing to work

to work

任何帮助是极大的赞赏。在此期间我会继续努力。

c arrays fgets eof strtok
1个回答
3
投票

这里有几个问题:

  1. 一旦字符串“重置”为新值,您就不会再次调用token = strtok(string, " \n");,因此strtok()仍然认为它正在标记您的原始字符串。
  2. strtok正在返回指向string内部“substrings”的指针。您正在更改string中的内容,因此您的第二行有效地破坏了您的第一行(因为string的原始内容被覆盖)。

要做你想做的事,你需要将每一行读入不同的缓冲区或复制strtok返回的字符串(strdup()是单向的 - 只记得free()每个副本......)

© www.soinside.com 2019 - 2024. All rights reserved.