Reputation: 231
I wrote a a function that has two arguments and therefore can concatenate 2 arrays of character strings. However, I need to use the same function to concatenate five arguments. That's where I am stuck, because my function does not work properly. I keeps only the last append. I pasted the code bellow. Your help will be appreciated. I wrote the code in C++, and I am using dev-C++.
#include<iostream>
#include<conio.h>
using namespace std;
char *Append(char *str, char *add)
{
int m=5;
static char buffer[150];
char *p=buffer;
while(*p++=*str++);
p--;
while(*p++=*add++);
return buffer;
}
int main()
{
static char *buffer1;
char *temp=" ";
char *str="Be, ";
char *add="or not to be, ";
char *str3="that's the question ";
char *str4="Whether 'tis Nobler in the mind to suffer ";
char *str5="The Slings and Arrows of outrageous Fortune,";
buffer1=Append(str, add);
cout<<buffer1;
///while(*temp++=*buffer1++);//where the problem starts!
/// temp--;
Append(temp, str); ///i am trying to append all strings into temp!!
buffer1=Append (temp, add);
cout<<endl<<buffer1;
getch();
return 0;
}
Upvotes: 0
Views: 395
Reputation: 88155
You're writing the concatenated string into a static buffer (static char buffer[150];
). Every time you call the append function, you write into the same buffer, which means you overwrite the string created by the previous call to append.
buffer1=Append(str, add); // buffer1 contains "Be, or not to be, "
Append(temp, str); // buffer1 now contains " Be, " even though you don't assign the result of Append to buffer1
However, you can still make it work if you do:
buffer1=Append(str, add);
Append(buffer1, str3);
Append(buffer1, str4);
Append(buffer1, str5);
Though you have to be careful not to overrun your buffer.
This works because when you pass buffer1 in as the first string the append function's first step becomes copying the previously concatenated string into itself, and the second step is to add on the new string.
Upvotes: 4
Reputation: 11
your question is not completely clear to me.Still,assuming that you want Append() to be used multiple times to concatenate consecutive 5 string, use main() like this.
int main()
{
static char *buffer1;
char *temp=" ";
char *str="Be, ";
char *add="or not to be, ";
char *str3="that's the question ";
char *str4="Whether 'tis Nobler in the mind to suffer ";
char *str5="The Slings and Arrows of outrageous Fortune,";
buffer1=Append(str, add);
cout<<buffer1;
///while(*temp++=*buffer1++);//where the problem starts!
/// temp--;
buffer1=Append(buffer1, str3); ///i am trying to append all strings into temp!!
buffer1=Append(buffer1,str4);
buffer1=Append(buffer1,str5);
cout<<endl<<buffer1;
getch();
return 0;
}
Upvotes: 1