gpt4 book ai didi

c - strtok() C 字符串到数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:24 25 4
gpt4 key购买 nike

目前正在学习 C,在将 C 字符串标记传递到数组时遇到了一些问题。行通过标准输入输入,strtok 用于拆分行,我想将每个行正确地放入一个数组中。退出输入流需要 EOF 检查。这是我所拥有的,设置它会将 token 打印回给我(这些 token 将在不同的代码段中转换为 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 信号之前多行流式传输。

例如,给定输入:

这一行就可以了

程序返回:

这个
线
将要

很好

但是如果给出:

这些都不是

开始工作

它返回:

开始工作

开始工作

工作

非常感谢任何帮助。在此期间,我会继续努力。

最佳答案

这里有几个问题:

  1. 一旦字符串“重置”为新值,您就永远不会再次调用 token = strtok(string, "\n");,所以 strtok() 仍然认为它正在标记化您的原始字符串。

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

    <

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

关于c - strtok() C 字符串到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52323463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com