C Question

C language: How do I convert a string parameter from a command line into an array of individual characters?

here is a part of my code:

int main(int argc, char*argv[])
{
//This section shows the statistic of the program
int a;

printf("The number of arguments is :%d \n", argc);

for(a=0; a<argc; a++)
{
printf("argc %d is %s \n",a, argv[a]);
}


Based on the code above, the second command line argument argv[1] will be a .txt file.

The third command line argument argv[2] will be entered as a string such as "monkey".

I need to know how to store the second command line argument "monkey" as an array of individual character so it will look somethings like this:

char key[6];
key[0]= 'm';
key[1]= 'o';
key[2]= 'n';
key[3]= 'k';
key[4]= 'e';
key[5]= 'y';

Answer

I hope to help you.

Try this:

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


int main(int argc, char*argv[])
{
        //This section shows the statistic of the program
        int a;

        printf("The number of arguments is :%d \n", argc);

        for(a=0; a<argc; a++)
        {
                printf("argc %d is %s \n",a, argv[a]);
        }

        int len = strlen(argv[2]+1);

        int key[10];
        int i = 0;
        for(i = 0; i <= len; i++)
        {
                key[i] = argv[2][i];
        }

        for (i = 0; i <= len; i++)
        {
                printf("key[%d] = %c\n", i, key[i]);
        }
}