d2jsp
Log InRegister
d2jsp Forums > Off-Topic > General Chat > Homework Help > C++ Combining Two Char Arrays Into A Third One. > Also Known As C_strings - 25fg
Add Reply New Topic New Poll
Member
Posts: 96
Joined: May 31 2012
Gold: 565.00
Mar 7 2015 10:04pm
can't figure this one out.

I need to start with a 10length first name given first name, ask for an age, then ask for a last name.
Then combine 10length firstname, and 10length lastname, into fullname.


I don't know which operator to use to get it.

I was thinking strcat. but that seems to be used for (array, "random string") rather than (array1, array2).

it seems to work, but it reduces the size of the fullname, down to 10.

-------
#include <iostream>
#include <string>
using namespace std;

void displayInfo(char fullName[ ], int age);
int main()

{

int age;
char firstName[10] = "Tom";
char lastName[10] = { '\0' };
char fullName[20] = { '\0' };

cout << "Enter your age: ";
cin >> age;
cout << "Enter your last name: ";

cin.ignore();
cin.getline(lastName, 10);
strcat_s(firstName, " ");
strcat_s(firstName, lastName);
strcat_s(fullName, firstName);
cout << fullName;
displayInfo(fullName, age);

system("pause");
return 0;
}

void displayInfo(char fullName[ ], int age)
{

cout << "Hello " << fullName << "You are " << age << "years old.";


}


-----

I wasn't sure to post here or in the C++ forum, but I figured since it was basic, here would work.

25fg

This post was edited by thestoryofisaac on Mar 7 2015 10:09pm
Member
Posts: 39,205
Joined: Jun 25 2006
Gold: 13.21
Mar 10 2015 09:42pm
I suggest using strings to manipulate your char arrays instead


Code
void displayInfo(char fullName[], int age);
int main()

{

int age;
char firstName[10] = "Tom";
char lastName[10] = { '\0' };
char fullName[20] = { '\0' };

cout << "Enter your age: ";
cin >> age;
cout << "Enter your last name: ";

cin.ignore();
cin.getline(lastName, 10);
cout << (string)firstName + " " + (string)lastName << endl; //C-style casting from char arrays to strings
strcpy_s(fullName,( (string)firstName + " " + (string)lastName).c_str());

displayInfo(fullName, age);

system("pause");
return 0;
}


This post was edited by LeB on Mar 10 2015 09:45pm
Go Back To Homework Help Topic List
Add Reply New Topic New Poll