Copying Char Arrays and Concatenation

Here my start. I need to copy the first name to a new array using a loop and then get the concatennation of the first and last name. I can't use strings..
Example output would be:
-Your first name is Paul and a copy of your name is Paul.
-Your first name is Paul and your last name is Smith so the concatenation is SmithPaul.
Any input is appretiated! Thanks
-----------------------------------------------------------
#include <iostream>
using namespace std;

int main ()
{
char name1[10];
char name2[10];

cout << "Enter first name ";
cin >> name1;

cout << "Enter last name ";
cin >> name2;
Last edited on
You could do it with new and pointers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

char* copyCharArray(char toCopy[], unsigned int size);

int main ()
{
  unsigned int size = 10; // 10 is ridiculously small for names. What about someone
                                       // called Schwartzenegger?
  char name1[size];
  char name2[size];
  char *copyName1;
  copyCharArray(copyName1, size);
   
  cout << "Enter first name ";
  cin >> name1;

  cout << "Enter last name ";
  cin >> name2;

  delete[] copyName1;

  return 0;
}

char* copyCharArray(char toCopy[], unsigned int size){
  char *copy = new char[size];
  for(int i = 0; i < size; i++){
    copy[i] = toCopy[i];
  }
  return copy;
}


I have not tested the code. But why would someone not use strings? You could use a library for cstrings, which could do that. Or you could simply use the string class. The problem with the above function is, that the function uses new but the user has to delete it somewhere else.

You could although write your own string class and use operator overloading, which would avoid this. This would make the code much easier to write.

I'm a beginner, too. So please don't blame me, if this code is not working.
Topic archived. No new replies allowed.