我已经被困在这几个小时了,我需要将一个字符串连接到另一个字符串的末尾,然后将结果存储在第三个字符串中(不使用预先构建的函数。我有一个我试图将我的结果存储到另一个字符串中的困难时期,我能够看到我想要的东西,但是它会导致无限循环并且似乎没有效果。任何人都可以对此有所启发吗?
#include <iostream>
using namespace std;
void Concat(char arr1[], char arr2[], char arr3[]);
int main(){
char arr1[] = {"Hello how are you? \0 "};
char arr2[] = { "The weather was cloudy today, so it rained. \0" };
char arr3[] = { "Coffee is a great way to start the day. \0" };
Concat(arr1, arr2, arr3);
}
void Concat(char arr1[], char arr2[], char arr3[]){
while (arr1 != '\0' && arr2 != '\0') {
// (This outputs what a want, haveing string 2 concat to the end of the firs string)
// However there is no way to save it to another array or stop the infinte loop.
//cout << arr1 << arr2 << endl;
arr1 + arr2 = arr3; // syntax error
}
}
答案 0 :(得分:0)
快速解决您的问题:
void Concat(const char* input1, const char* input2, char* output)
{
int i = 0;
do {
output[i] = *input1;
i++;
input1++;
} while (*input1 != '\0');
do {
output[i] = *input2;
i++;
input2++;
} while (*input2 != '\0');
}
注意:我不检查输出缓冲区是否有足够的内存,我希望您可以自己编辑它。
答案 1 :(得分:0)
您可能想尝试这样:
#include <iostream>
void concat(const char *arr1, const char *arr2, char *arr3);
int main(){
const char *arr1("abc");
const char *arr2("def");
char arr3[10];
concat(arr1, arr2, arr3);
std::cout << "arr3 is " << arr3 << std::endl;
}
void concat(const char *arr1, const char *arr2, char *arr3){
if (arr1) {
while(*arr1 != '\0') {
*arr3 = *arr1;
++arr1; ++arr3;
}
}
if (arr2) {
while(*arr2 != '\0') {
*arr3 = *arr2;
++arr2; ++arr3;
}
}
*arr3 = '\0';
}
答案 2 :(得分:0)
您应该尝试按索引连接索引。在以下代码中,我首先在arr1
中添加arr3
的所有内容,然后arr2
concat的内容添加arr3
#include <iostream>
using namespace std;
void Concat(char arr1[], char arr2[], char arr3[]);
int main(){
char arr1[] = {"Hello how are you? \0 "};
char arr2[] = { "The weather was cloudy today, so it rained. \0" };
char arr3[] = { "Coffee is a great way to start the day. \0" };
Concat(arr1, arr2, arr3);
std::cout << "arr3 is " << arr3 << std::endl;
}
void Concat(char arr1[], char arr2[], char arr3[]){
if (arr1) {
while(*arr1 != '\0') {
*arr3 = *arr1;
++arr1; ++arr3;
}
}
if (arr2) {
while(*arr2 != '\0') {
*arr3 = *arr2;
++arr2; ++arr3;
}
}
*arr3 = '\0';
}