C - How to take string as arguments

I have this code that will take user input and do something with it.

int main ()
    char key[] = "quit";
    char buffer[80];
    do {
        printf ("CMD> ");
        scanf ("%s",buffer);
    } while (strcmp (key,buffer) != 0);
    printf ("Bye.\n");
    return 0;

I want to integrate other commands. So of I ask a user to input a command like a string:

CMD > xxx -a 32

And he gives me a string "xxx -a 32". How can I take them as arguments?

So I can use case to call a functions with those arguments like:

switch(xxx) {  // first arg

   case (-a)  :  // second arg
      callAFunction(32);  // third arg 


As ameyCU pointed out, you cannot use switch that way because you need to have the variable name to use with switch at compile time. However, you can use strcmp to compare the string argument (xxx) that user enters at run time.

To split user input into multiple arguments, you can try strtok, something along this line (this assume enters exactly three arguments, and there is no error checking yet).

    printf ("CMD> ");
    // scanf ("%s",buffer);   // better use fgets
    fgets( buffer, sizeof( buffer ), stdin );

    char *args[3] = { NULL };
    char *pch;

    pch = strtok (buffer," ");
    int i = 0;
    while (pch != NULL)
        args[i++] = pch;
        pch = strtok (NULL, " ");

    for( i = 0; i < 3; i++ )
        if( args[i] != NULL )
            printf( "args[%d] = %s\n", i, args[i] );

You can do one thing the following format: scanf("%s %c %d",arg1,&arg2,&arg3); But here also you are not done in arg1 the string is stored which is not a variable so you can not put it as a argument to switch command. Try to use arg1 for this purpose

Need Your Help

Menu glitchy on top of slideshow

javascript css slideshow onmouseover

I have implemented the following set up (after being requested):

htaccess files in sub folders

apache .htaccess mod-rewrite

I have a development environment with a folder structure like;