Need help with a easy programming problem in c++

dapatient

Member
Oct 13, 1999
140
0
0
I have a program (encrypt.exe) that waits for user input using cin.getline()
to my understanding, cin.getline will take the input and parse it out over an array.

so for example lets say i run the program and it asks for text...
it type in "test"

my progarm will basically do this:
scratch[0] = 't';
scratch[1] = 'e';
scratch[2] = 's';
scratch[3] = 't';
scratch[4] = '\0';

Now what i want to do is avoid having the user input text by passing the text through the command line.
I am using main(int argc, char **argv) to do this.
so if i run the program like this... encrypt.exe test
i want it to do the same as above.
but the problem is "test" is entered in as one long char into argv[1].

how can i parse argv[1] to scratch[] so i get the same result as above... i.e.
scratch[0] = 't';
scratch[1] = 'e';
scratch[2] = 's';
scratch[3] = 't';
scratch[4] = '\0';

i know i can probably write some simple loop...but what fucition do i use to parse argv[1]?

i hope i made my probelm clear.

Thaks guys
 

njmodi

Golden Member
Dec 13, 2001
1,188
1
71
You answer your own question - but there are other ways to do the same thing:

i know i can probably write some simple loop...but what fucition do i use to parse argv[1]?

Just use a for loop - and use strlen(argv[1]) as your loop limit... something like:

for (j=0;j < strlen(argv[1]); j++)
{
scratch[j]=argv[1][j];
}

2. You can also use a strcpy command to copy the string from argv into scratch.

3. You can just declare scratch as a char *, and make it point to the address of argv[1].

Without seeing the context or the remaining code, its hard to tell which way will work best (although 1 and 2 are the same thing).

With 3. you aren't really declaring a second scratch array - you are just using the scratch variable as a pointer to the memory allocated to the argv[] params.

 

dapatient

Member
Oct 13, 1999
140
0
0
njmodi, thank you for taking the time to respond.

You're advice solved my probelm.


My program is working like a charm now.

Bless you.