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!
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:
#include <iostream>
#include <string>
usingnamespace 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 = newchar[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