2

所以我的任务是:

使用strncpy和中的strncat函数#include<cstring>,实现一个函数

void concat(const char a[ ], const char b[ ], char result[ ],
                 int result_maxlength)

将字符串ab缓冲区连接起来result。确保不要超出结果。它可以容纳result_maxlength字符,不包括\0终止符。(也就是说,缓冲区有 buffer_maxlength + 1可用的字节。)一定要提供一个 '\0' 终止符。

我的解决方案(到目前为止)如下,但我不知道我做错了什么。当我实际运行程序时,我不仅会收到运行时检查失败 2 错误,而且我不确定应该在哪里添加\0终止​​符,或者即使我应该使用strncat而不是strncpy. 希望有人能引导我朝着正确的方向前进。是的,这就是硬件。这就是为什么我说只要引导我朝着正确的方向前进,这样我就可以尝试弄清楚: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);
}
4

3 回答 3

2

至少你result在第一个之前是未初始化strncatconcat

编辑:是的,正如 Michael Burr 指出的那样,你的结果大小应该随着你的进步而改变,并从一开始就计算出来。实际上,您选择的名称具有误导性,因为它是源的最大大小,而不是目标。

于 2012-08-31T14:38:04.930 回答
2

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.

于 2012-08-31T14:38:38.350 回答
1
  1. strncpy from a to result (whatever is smaller, lenght of a or result_maxlength)
  2. strncat from b to remaining of result (whatever is smaller, lenght of b or result_maxlength- lenght of a)

  3. 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)

于 2012-08-31T14:47:27.417 回答