如何将两个字符或字符串数组附加到一个数组中
How do you append two char or string arrays into one array?
我有一个问题要求我提示用户输入名字和姓氏。声明第三个数组以保存用逗号和空格分隔的姓氏和名字。使用循环一次循环访问一个字符的名称,并将它们存储到全名数组中。
这听起来很容易,但我遇到了很多麻烦。我已经尝试了多种方法来做到这一点,甚至是问题没有要求的方式,比如strncpy或memcpy或strncat。也许我只是理解不正确。
这是我目前拥有的:
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;
感谢您的任何帮助。
不使用任何库函数的一个可能答案是:
// 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;
使用 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 ' ' will be appended to FirstLast and this will mark end of FirstLast string.
}
//else {
// FirstLast[i] = FirstName[i - 5];
//}
}
正确的方法是:
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] = ' ';
当然,LengthOf(FirstLast)
至少应该LengthOf(FirstName) + LengthOf(LastName) + 2(for comma and space) + 1 (null terminating character)