In my code I am trying to add two strings together, however for some reason I can't seem to get the correct return type for my stringAdd function. I want to be able to return a c-string. And my implementation doesn't seem to work either. Any suggestions?
#include <iostream>
#include<cstring>
using namespace std;
int stringLength(char *); // Function prototype
char stringAdd(char *strPtr, char *strPtr2);//Function prototype
int main()
{
const int SIZE = 51; // Array size
char letter; // The character to count
char word1[SIZE] = "Happy ";
char word2[SIZE] = "Birthday";
cout <<"Your first c-string is: "<<word1<<"Your second c-string is: "<<word2<<"\n";
cout << "The length of your first c-string is: ";
cout << stringLength(word1) << " chars long.\n";
cout << "The length of your second c-string is: ";
cout << stringLength(word2) << " chars long.\n";
if (SIZE >= (stringLength(word1) + stringLength(word2) + 1))
{
cout << "we are gunna add ur strings";
stringAdd(word1, word2);
}
else
{
cout << "String1 is not large enough for both strings.\n";
}
return 0;
}
int stringLength(char *strPtr)
{
int times = 0; // Number of times a char appears in the string
// Step through the string each char.
while (*strPtr != '\0')
{
if (*strPtr != '0') // If the current character doesnt equals the null terminator...
times++; // Increments the counter
strPtr++; // Goes to the next char in the string.
}
return times;
}
Up until this point my code works fine however the function below doesn't seem to work at all. I'm not sure how I can add two c-strings using reference
char stringAdd(char *strPtr, char *strPtr2)
{
int size1;
int size2;
size1= stringLength(strPtr);
int j=size1+1; // counter set to the num of chars in the first c-string
int i = 0; // counter for to add to the 2nd c-string
size2= stringLength(strPtr2);
size1=+size2;
char newWord[size1];
for(int i=0;i<size1;i++)
newWord[i] = *strPtr[i]
for(int j=0;j<size2;j++)
newWord[i]= *str
}
if (*strPtr != '0'), you forgot to escape the0– you probably meant'\0'.