开发者

While Loop clearing my array? (C)

I've been hard at this problem for a bit and am wondering if anybody can find what Im doing wrong. Im reading user input from stdin, breaking up the string they input via strtok(), and storing it into an array of char *'s. The array of char *'s is defined outside of the while loop.

So: a user types in input via stdin, and an array is filled with strings with each word from the command.

The thing is, if the user simply hits enter I want the array to MAINTAIN it's value! I want the same values to stay in the array...so I can re-execute the same command. It appears that the while loop is clearing my array of char*'s instead. Here's code:

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) 
        {
            prin开发者_开发问答tf("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]);
}      

The printf's CHECK 1, CHECK 2,and CHECK 3 all print nothing if the user hits enter. In the case they last typed "step" I want "step" to stay in the array and thusly be executed again!


You are filling the commands array with pointers to the stuff array. That array is being overwritten by the fgets each time (probably replacing the first character with null). You would need to copy the data out to preserve it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜