gpt4 book ai didi

c - While 循环清除我的数组? (C)

转载 作者:行者123 更新时间:2023-11-30 14:28:02 24 4
gpt4 key购买 nike

我已经在这个问题上努力了一段时间,想知道是否有人能发现我做错了什么。我从 stdin 读取用户输入,分解他们通过 strtok() 输入的字符串,并将其存储到 char * 数组中。 char * 数组是在 while 循环外部定义的。

因此:用户通过 stdin 键入输入,数组中将填充命令中每个单词的字符串。

问题是,如果用户只是按 Enter 键,我希望数组保持它的值!我希望相同的值保留在数组中......这样我就可以重新执行相同的命令。看来 while 循环正在清除我的 char* 数组。代码如下:

char *commands[3];
char *result = NULL;
char delims[] = " "; //a space AND a tab!
while (1) {

printf(PROMPT);

//Gathers user input!
char *input;
char stuff[230];
input = fgets(stuff, 230, stdin);

printf("input has length %i\n", strlen(input));
int helper = strlen(input);
int i = 0;

result = strtok(input, delims);
printf("helper has length %i\n", helper);
printf("commands[0] CHECK 1:%s", commands[0]);
if (helper >1)
{
while( result != NULL)
{
printf("while gets hit!\n");
if (i < 4)
{
commands[i] = result;
result = strtok(NULL, delims );
i++;
}
}
}


printf("commands[0] is CHECK 2:%s", commands[0]);
if (strncmp(commands[0], "step", 4) == 0)
{
lc3_step_one(p);
}
printf("commands[0] is CHECK 3:%s", commands[0]);
}

如果用户按回车键,printf 的 CHECK 1、CHECK 2 和 CHECK 3 都不会打印任何内容。在他们最后输入“step”的情况下,我希望“step”保留在数组中,从而再次执行!

最佳答案

您正在使用指向 stuff 数组的指针填充命令数组。该数组每次都会被 fget 覆盖(可能用 null 替换第一个字符)。您需要将数据复制出来以保留它。

关于c - While 循环清除我的数组? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867078/

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