目前正在学习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
任何帮助都是非常感谢的。在此期间,我将继续努力。
发布于 2018-09-14 08:40:58
这里有几个问题:
一旦字符串被“重置”为一个新值,你就再也不会调用
strtok()
仍然认为它是在标记化你的原始string.
strtok
,返回指向string
中“子字符串”的指针。您正在更改string
中的内容,因此第二行有效地损坏了第一行(因为string
的原始内容是overwritten).要完成您想要的操作,您需要将每一行读取到不同的缓冲区中,或者复制strtok
返回的字符串(strdup()
是一种方法--只需记住对每个副本执行free()
...)
https://stackoverflow.com/questions/52323463
复制相似问题