简体   繁体   中英

How do you append two char or string arrays into one array?

I have a question asking me to prompt a user for first and last names. Declare a third array to hold last and first name separated by a comma and a space. Use loops to iterate through the names one character at a time, storing them into the full name array.

It sound easy enough, but I'm having so much trouble with it. I've tried multiple ways to do it, even ways the question doesn't ask for, like strncpy or memcpy or strncat. Maybe I'm just not understanding correctly.

This is what I currently have:

char FirstName[15];
char LastName[15];
char FirstLast[30];

cout << "Enter your first name: ";
cin >> FirstName;
cout << "Enter your last name: ";
cin >> LastName;


for (int i = 0; i<30; i++)
{
    if (i < 15) {
        FirstLast[i] = LastName[i];
    }
    else {
        FirstLast[i] = FirstName[i - 5];
    }
}


cout << FirstLast;

Thanks for any help.

Use std::string

string FirstName, LastName, FirstLast;

cout << "Enter your first name: ";
cin >> FirstName;
cout << "Enter your last name: ";
cin >> LastName;

FirstLast = LastName + ", " + FirstName;

cout << FirstLast;
for (int i = 0; i<30; i++)
{
    if (i < 15) {
        FirstLast[i] = LastName[i];  
        //if LastName is less than 15 characters then garbage and probably '\0' will be appended to FirstLast and this will mark end of FirstLast string.
    }
    //else {
    //  FirstLast[i] = FirstName[i - 5];
    //}
}

Correct way would be:

    int i = 0, j = 0;
    while(LastName[j])
    {
        FirstLast[i] = LastName[j];     
        ++i;
        ++j;
    }
    FirstLast[i] = ',';
    ++i;
    FirstLast[i] = ' ';
    ++i;
    j = 0;
    while(FirstName[j])
    {
        FirstLast[i] = FirstName[j];    
        ++i;
        ++j;
    }
    FirstLast[i] = '\0';        

Ofcourse, LengthOf(FirstLast) should be atleast LengthOf(FirstName) + LengthOf(LastName) + 2(for comma and space) + 1 (null terminating character)

One possible answer without using any of the library functions would be:

// copy last name
int i = 0;
for (i = 0; LastName[i] != 0; ++i)
    FirstLast[i] = LastName[i];

// add , and space
FirstLast[i++] = ',';
FirstLast[i++] = ' ';

// append first name
for (int j = 0; FirstName[j] != 0; ++j)
    FirstLast[i++] = FirstName[j];

// Terminate the string
FirstLast[i] = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM