DEV Community

Olalekan Omotayo
Olalekan Omotayo

Posted on

Parsing user input to separate commands and arguments

Here's an example code in C language for parsing user input to separate commands and arguments:

include

include

define MAX_ARGS 10

int main() {
char input[100];
char *token;
char *args[MAX_ARGS];
int arg_count = 0;

while(1) {
    arg_count = 0;

    printf("Enter a command: ");
    fgets(input, 100, stdin);

    // Tokenize input string by whitespace
    token = strtok(input, " \n");

    // Parse arguments and store in args array
    while(token != NULL && arg_count < MAX_ARGS) {
        args[arg_count++] = token;
        token = strtok(NULL, " \n");
    }

    // Check for empty input
    if(arg_count == 0) {
        continue;
    }

    // Print command and arguments
    printf("Command: %s\n", args[0]);
    printf("Arguments: ");
    for(int i=1; i<arg_count; i++) {
        printf("%s ", args[i]);
    }
    printf("\n");
}

return 0;
Enter fullscreen mode Exit fullscreen mode

}

In this code, we first declare a character array input with a size of 100, which we will use to store the user's input. We also declare a character pointer token to represent each individual token in the input string, and an array of character pointers args to store the parsed arguments. We also set a constant MAX_ARGS to limit the number of arguments.

Within the loop, we use the printf function to display the prompt "Enter a command: " to the user. We then use the fgets function to read the user's input from the standard input stream stdin and store it in the input array.

We then use the strtok function to tokenize the input string by whitespace and newline characters. The strtok function takes two arguments: the string to tokenize and a string containing the delimiters to use. In this case, we use whitespace and newline characters as delimiters.

We then loop through each token and store it in the args array, incrementing the arg_count variable to keep track of the number of arguments. We also use a check to ensure that we don't exceed the maximum number of arguments.

After parsing the arguments, we check for empty input and continue to the next iteration of the loop if no arguments were entered. Otherwise, we print the command and arguments using the printf function.

Top comments (0)