I know a string concatenation question has been asked to death in SE. But to the best of my knowledge,I’ve gone through all the questions that could help me, in vain.
This is what I am hoping to accomplish with this program:
Initially I have a=0 and b=1, for n=0 and n=1 respectively.
For the next input i.e from n=3 onwards, my result should be concatenation of the previous two strings. (Like a Fibonacci sequence; only the addition is replaced by concatenation)
So,for example:
For n=3, my output should be “10”.
For n=4, my output should be “101”
For n=5, my output should be “10110”
There is no logical problem with the code I’ve written,but I’m getting a SIGSEGV error and I don’t see why.
#include <iostream>
#include<new>
#include<string.h>
using namespace std;
int main()
{
long int n,i;
char *a="0";
char *b="1";
char *c=new char[100000];
cout<<"Enter a number n:";
cin>>n;
for(i=0;i<n;i++)
{
strcat(b,a);
strcpy(a,b);
}
cout<<"\nRequired string="<<b;
}
What am I doing wrong?
strcat(b,a);invokes undefined behaviour becausebpoints to a string literal.Since this is C++, I suggest you use
std::stringand the+operator. Or astd::stringstream.