strings to char array

Guys, I'm having a problem to copy a string to a char array;
I need to read two strings and than put the content of them into a dynamically allocated char array;

so far I've read both strings with getline and created the char* array, But how do I put the content of the strings in it?
Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cstring>

using namespace std;

int main(){

    string vet1, vet2;
    
    getline(cin,vet1);
    getline(cin,vet1);
    
    unsigned int size = strlen(vet1) + strlen(vet2);
    
    char* merge = new char[size];
    
    delete[] merge;
    return 0;
    }
Firstly, remember that you'll need an extra char to hold the '\0' c-string terminator.
Then perhaps strcpy followed by strcat, using the c_str() member of string to get the underlying chars:
1
2
3
char* merge = new char[size + 1];
strcpy(merge, vet1.c_str());
strcat(merge, vet2.c_str());


I just noticed that you're reading both strings into vet1, so you may want to fix that.
Last edited on
ok than, but how do I move tem to the char array manually? without using libraries (except for strlen).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string a, b;
   int extra = 1;       // set extra = 0 for a straight char array, or 1 for a null-terminated C-string

   cout << "Input two strings, pressing enter after each\n";
   getline( cin, a );
   getline( cin, b );

   char *combo = new char[a.size()+b.size()+extra];
   char *p = combo;
   for ( int i = 0; i < a.size(); i++, p++ ) *p = a[i];
   for ( int i = 0; i < b.size(); i++, p++ ) *p = b[i];
   if ( extra == 1 ) *p = '\0';

   cout << "Result is " << combo;

   delete [] combo;
}


Input two strings, pressing enter after each
Persona
 non grata
Result is Persona non grata
Last edited on
@lastchance If extra = 0, then the result is a valid character array, but it isn't a valid c-string, hence
 
    cout << "Result is " << combo;
would not be valid.
I only gave the option because I wasn't actually sure whether the OP wanted a straight char array or a C-string.

The cout statement is only there to test the outcome when extra = 1, but, for good or bad, cpp-shell doesn't seem to mind whether it is 0 or 1.
Topic archived. No new replies allowed.