简体   繁体   English

如何将两个char或string数组追加到一个数组中?

[英]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. 我尝试了多种方法来做到这一点,甚至是问题不要求的方法,例如strncpy或memcpy或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 使用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) 当然, LengthOf(FirstLast)应该至少是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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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