So my assignment is:
Using the
strncpy
andstrncat
functions in#include<cstring>
, implement a functionvoid concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength)
that concatenates the strings
a
andb
to the bufferresult
. Be sure not to overrun the result. It can holdresult_maxlength
characters, not counting the\\0
terminator. (That is, the buffer hasbuffer_maxlength + 1
bytes 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);
}
At the very least your result
is uninitialized before the first strncat
in concat
.
EDIT : And yes, as Michael Burr points out your result size is supposed to be changing as you progress and calculated from the very start. Actually, it is misleading name you picked, because it is the max size of source, not destination.
The last argument to strncat()
represents the remaining space available in the buffer - not the full size of the buffer.
Also note that that argument includes the spot that the terminating null character will need, so you'll need to account for that since the spec for concat()
is otherwise.
Finally, according to the concat()
spec, the result placed in the buffer should not be concatenated to the existing contents of the buffer (those contents should be replaced). Also, make sure you test that your function properly handles a zero length result_maxlength
argument being passed in.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.