#include<iostream>;
usingnamespace std;
int strlen(char []);
void strcat(char S1[], char S2[], int size_1, int size_2);
constint SIZE = 100;
constint MAX = 100;
int main(){
int lenght_word1 = 0, lenght_word2 = 0;
char word1[SIZE];
char word2[SIZE];
char word3[MAX];
cin >> word1;
lenght_word1 = strlen(word1);
cin >> word2;
lenght_word2 = strlen(word2);
strcat(word1, word2, lenght_word1, lenght_word2);
system("pause");
return 1;
}
int strlen(char array[]){
int i = 0;
int lenght;
if (array[0] == 0){
lenght = 0;
}
else{
do{
i = i + 1;
lenght = i;
} while (array[i] != 0);
}
return lenght;
}
void strcat(char S1[], char S2[], int size_1, int size_2){
char S3[MAX];
for (int a = 0; a < size_1; a++){
S3[a] = S1[a];
}
S3[size_1] = 32;
for (int b = (size_1 + 1); b < (size_1 + size_2); b++){
S3[b] = S2[b];
}
S3[size_1 + size_2 + 1] = 0;
cout << S3 << endl;
}
Hello i have been trying to do a function that unites strings entered by user,
i need to do this without any other libraries but i keep getting an output of the first word and dots. Please help, thanks :).
for (int b = (size_1 + 1); b < (size_1 + size_2); b++){
S3[b] = S2[b];
}
What will the initial value of b be? 6. So we get: S3[6] = S2[6];
See how b isn't a valid index for S2 (I guess that is better said as not a valid index for the word in S2)?
You need a separate index for S3 and S2 (also, since you put a space between the two words you need to add one to the total length). Something like this should work:
1 2 3
for (int b = (size_1 + 1), c = 0; b < (size_1 + size_2 + 1); b++, c++){
S3[b] = S2[c];
}
char* s3 = newchar[newSize + 1]; Do not forget to add space for null terminator, as right now s3[newSize] = '\0'; is UB. Remember, a[size] have only elements with indexes from 0 to size - 1!