首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >strtok() C-数组字符串

strtok() C-数组字符串
EN

Stack Overflow用户
提问于 2018-09-14 08:34:46
回答 1查看 1.7K关注 0票数 0

目前正在学习C语言,在将c-string标记传递给数组时遇到了一些问题。行通过标准输入进入,strtok用于拆分行,我希望将每行正确地放入一个数组中。退出输入流需要EOF检查。下面是我所拥有的,设置好让它将令牌打印回给我(这些令牌将在不同的代码段中转换为ASCII,只是为了让这部分先工作)。

代码语言:javascript
复制
#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

任何帮助都是非常感谢的。在此期间,我将继续努力。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-14 08:40:58

这里有几个问题:

一旦字符串被“重置”为一个新值,你就再也不会调用

  • 了,所以strtok()仍然认为它是在标记化你的原始string.

  • strtok,返回指向string中“子字符串”的指针。您正在更改string中的内容,因此第二行有效地损坏了第一行(因为string的原始内容是overwritten).

要完成您想要的操作,您需要将每一行读取到不同的缓冲区中,或者复制strtok返回的字符串(strdup()是一种方法--只需记住对每个副本执行free() ...)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52323463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档