I am working on a little hobby project, it reads user input and then stores it in a pointer to char array. The problem is that the output is not correct. So i dont know if it is the output, or the storing that is wrong. I am used to using C++, but always used vector <string> in c++ to create my list. Here is my code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_BUFFER_SIZE 512

int main(int argc, char *argv[])
{
    char input[MAX_BUFFER_SIZE];
    char *commands[20];
    char *token;
    int counter;
    bool _continue = true;

    while(_continue)
    {
        counter = 0;
        // Read user input.
        printf(">");
        fgets(input, MAX_BUFFER_SIZE, stdin);

        // Split string.
        token = strtok(input, " ");
        while(token != NULL)
        {
            token = strtok(NULL, " ");
            if(counter > 20)
            {
                printf("\n<x>To many commands.\n");
                break;
            }
            else
            {
                commands[counter] = token;
            }
            counter++;
        }

        for(int i = 0; i < counter; i++)
            printf("%s\n", commands[i]);
    }

    return 0;
}

It gives this output when I enter h h:

h

(null)

I know that the (null) is a trailing character that i can just remove, but where is my second h?

move line 27 down to line 38 because you are throwing out the first token in the string.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.