【问题标题】:While Loop clearing my array? (C)循环清除我的数组? (C)
【发布时间】:2011-07-28 23:40:38
【问题描述】:

我一直在努力解决这个问题,我想知道是否有人能找到我做错了什么。我从标准输入读取用户输入,分解他们通过 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”留在数组中,从而再次执行!

【问题讨论】:

  • 什么意思?这是我正在上的一门课的项目。就我为解决问题所做的工作而言;实际上,我已经尝试了一种机制来阻止代码中已经存在的这种现象......但它并没有按照我想要的方式工作。

标签: c arrays string


【解决方案1】:

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

【讨论】:

  • strdup 将是一个很好的函数来复制字符串数据。完成后请记住 free 字符串指针。
猜你喜欢
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 2010-11-11
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
  • 2011-04-25
相关资源
最近更新 更多