Question

In C, I need to take a single string argument from argv [] and put it into another array so that I can iterate over the chars. How do I do this?

(this is to implement a Veginere Cypher FYI)

Was it helpful?

Solution

If you want to iterate over the characters of the nth entry in argv:

int i;
int len = strlen(argv[n]);
for (i = 0; i < len; i++)
    // do something with argv[n][i]

If you want to copy them somewhere else first (which is most likely not necessary) use strcpy() or strdup().

OTHER TIPS

You do not need to copy it into a separate string.

Here is how:

// argv is array of strings, or array of array of chars
int main( int argc, char** argv ) // here argv is an array of strings
{
    int i = 0;
    while( 1 )
    {
        if( argv[1][i] == '\0' )
            break; // argv[1][i] <- Current character of the first cmd-line arg
        i++
    }
}

or if you would really like to copy it to use a simple string, just set up a pointer to the start of the string like so:

char* firstArgument = argv[n]; // where n is the nth command line argument

You don't need to copy the string. You don't state that you are mutating the string (though argv is modifiable, I would probably leave it alone), so just iterate over it.

int main(int argc, char *argv[])
{
    if(argc < some_min_value) {
        print_usage();
        return -1;
    }

    for(int i = 0; argv[str_idx][i]; ++i) {
        char c = argv[str_idx][i];
        /* do something with c */
    }

    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top