c_string need help with output

firstName is assigned "Tom" and the lastName is input from user

and im having trouble using fullName = firstName + " " + lastName;
i remember the professor saying it wasn't allowed in c_strings
but i dont remember the proper way to do it.


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


int main()
{
char firstName[10] = "Tom";
char lastName[10];
char fullName[20];
int age;

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

cout << "\nEnter the last name: ";
cin.getline(lastName, 10);

//fullName = firstName + " " + lastName;

cout << "\n\nHello " << fullName << " .";
cout << "You are " << age << " years old." << "\n";



system("pause");
return 0;
}
#include <cstring> // shall add it


std::strcpy( fullName, firstName );
std::strcat( fullName, " " );
std::strcat( fullName, lastName );
You need to use strcpy() or one of its derivative functions to copy C strings.
Last edited on
thank you!
it won't let me input the last name

this is my output:

Enter your age: 21

Enter the last name:

Hello Tom .You are 21 years old.
Press any key to continue . . .


#include <iostream>
#include <string.h>
using namespace std;


int main()
{
char firstName[10] = {"Tom"};
char lastName[10];
char fullName[20];
char age[2];

cout << "Enter your age: ";
cin.getline(age, 2);

cout << "\nEnter the last name: ";
cin.getline(lastName, 10);
cout << "\n";

strcpy( fullName, lastName );
strcat( fullName, " " );
strcat( fullName, firstName);

puts(fullName);

system("pause");
return 0;
}
Last edited on
change to:


1
2
3
4
   char age[3];

   ...
   cin.getline(age, 3);


when using c-strings you have to cater for the null terminated character as well - functions like strcpy and strcat will usually fail if a c-string is not NULL terminated properly.

strncpy is considered safer to use.
Topic archived. No new replies allowed.