В моем коде я пытаюсь добавить две строки вместе, однако по какой-то причине я не могу получить правильный тип возвращаемого значения для моей функции stringAdd. Я хочу вернуть c-строку. И моя реализация тоже не работает. Какие-либо предложения?добавление двух c-строк в C++
#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;
}
Вплоть до этого момента мой код работает нормально, однако нижеследующая функция не работает вообще. Я не знаю, как я могу добавить два с-строку с использованием опорного
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
}
в вашем внутреннем 'если (* StrPtr = '0'!)', Вы забыли, спасаясь от '0' - вы, вероятно, имел в виду ' '\ 0' '. – mindriot