tags:

views:

76

answers:

2

Hi

As a Java programmer who wants to learn C, I try to create a command line based menu in C. The menu should read a line that is split by spaces that are divided into a matrix. Below are some Java code that does what I want: Can someone please help me to create a menu in C with this functionality?

while(scan.hasNextLine()) {
            String line = scan.nextLine();
            String [] command = line.split(" ");

            if(command[0].equals("c") && command[1] != null) {
                     ......

C:

char line[LINE_MAX];
    char *command;

    if(fgets(line, LINE_MAX, stdin) != NULL) {
        command = strtok(line," ");

        while(command != NULL) {
            printf("%s", command);
        }

    }
+1  A: 

Look at the documentation of fgets() (for replacing hasNextLine() and nextLine()) and strtok() (for replacing split()).

Edit: here is my edit on your try:

while (fgets(line, LINE_MAX, stdin) != NULL) {
    command = strtok(line, " ");

    if (command != NULL) {
        char *argument;

        printf("command = %s\n", command);
        while ((argument = strtok(NULL, " \n")) != NULL) {
            printf("\targument = %s\n", argument);
        }
    }
}
Edgar Bonet
Its hard to make some code out of this :(
@user Uhm, why don't you check the examples I linked to then?
Let_Me_Be
Above is my try! Not working well, I'm confused
Good try. It works with some modifications, see above.
Edgar Bonet
Thanks, this was a good solution :D
I need some more help to get this to work the way I want: A sentence is divided up when the sentence contains a space. How can I put each divided word into an array commands[]: ex: hello my friend, commands[0] = hello, commands[1] = my, commands[2] = friend. Can someone please give me a hand?
Just replace the printfs by something like `commands[i++] = argument`.
Edgar Bonet