So my assignment is:
Using the
strncpyandstrncatfunctions in#include<cstring>,
implement a functionvoid concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength)that concatenates the strings
aandbto the bufferresult. Be sure
not to overrun the result. It can holdresult_maxlengthcharacters,
not counting the\0terminator. (That is, the buffer has
buffer_maxlength + 1bytes available.) Be sure to provide a ‘\0’
terminator.
My solution (thus far) is below but I don’t know what I’m doing wrong. Not only do I get a run-time check failure 2 error when I actually run the program, but I’m unsure where I should be adding the \0 terminator or even if I should be using strncat rather than strncpy. Hopefully someone can lead me in the right direction. And yes this is hw. That’s why I said just lead me in the right direction so that I can try to figure it out :p
#include <iostream>
#include <cstring>
using namespace std;
void concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength);
int main()
{
char a[] = "Woozle";
char b[] = "Heffalump";
char c[5];
char d[10];
char e[20];
concat(a, b, c, 5);
concat(a, b, d, 10);
concat(a, b, e, 20);
cout << c << "\n";
cout << d << "\n";
cout << e << "\n";
return 0;
}
void concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength)
{
strncat(result, a, result_maxlength);
strncat(result, b, result_maxlength);
}
strncat from b to remaining of result (whatever is smaller, lenght of b or result_maxlength- lenght of a)
before every return just put a \0 at last position
result[result_maxlength-1] ='\0';It’s actually not specified WHAT to do if result is too short, should you add trailing 0 or not. I guess you’d better terminate that string.
tip : remaining of result is
result+strlen(a)