how to copy argv[1]?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(int argc, char *argv[]) 
{ 
   char * str1,*str2,*str3; 
    str1=argv[1];
    str2=argv[1];
   
     .........
     strcat(str1,"hello");
     cout<<str1;
     strcat(str2,"well");
     cout<<str2;

........

example d:>main test

str1 contains"testhello"
str2 contains"testhellowell"

but I only want str2 contains"testwell" not "testhellowell"

This wouldn't work because both str1 and str2 are pointers to the same location in memory and changing one affects the other one.

You could write something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(int argc, char *argv[])
{
    char str1[40];
    char str2[40];

    strcpy(str1, argv[1]);
    strcpy(str2, argv[1]);

    strcat(str1, "hello");
    printf("str1: %s\n", str1);
    strcat(str2, "well");
    printf("str2: %s\n", str2);
}

Use std::string.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main( int argc, char* argv[] )
{
    // assert( argc > 1 );
    std::string arg1 = argv[ 1 ] + std::string( "hello" );
    std::string arg2 = argv[ 1 ] + std::string( "well" );
    std::cout << arg1 << std::endl << arg2 << std::endl;
}
Last edited on
Topic archived. No new replies allowed.