[英]Concating a char array to the end of another char array (without built in functions)
我已經堅持了幾個小時,我需要將一個字符串連接到另一個字符串的末尾,然后將結果存儲在第三個字符串中(不使用預建函數。我很難試圖將我的結果存儲到另一個字符串中,我能夠瞥見我想要的東西但是它導致無限循環並且似乎沒有效果.任何人都可以對此有所了解嗎?
#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
}
}
快速解決您的問題:
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');
}
注意:我不檢查輸出緩沖區是否有足夠的內存等,希望你可以自己編輯。
你可能想嘗試這樣的事情:
#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';
}
您應該嘗試按索引連接索引。在下面的代碼中,我首先在arr3
添加arr1
所有內容,然后將arr2
內容與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';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.