gpt4 book ai didi

c++ - strncat 和 strncpy 帮助 C++

转载 作者:搜寻专家 更新时间:2023-10-31 00:42:16 24 4
gpt4 key购买 nike

所以我的任务是:

Using the strncpy and strncat functions in #include<cstring>, implement a function

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

that concatenates the strings a and b to the buffer result. Be sure not to overrun the result. It can hold result_maxlength characters, not counting the \0 terminator. (That is, the buffer has buffer_maxlength + 1 bytes available.) Be sure to provide a ‘\0’ terminator.

我的解决方案(到目前为止)如下,但我不知道自己做错了什么。当我实际运行程序时,我不仅收到运行时检查失败 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);
}

最佳答案

至少在 concat 中的第一个 strncat 之前,您的 result 是未初始化的。

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

关于c++ - strncat 和 strncpy 帮助 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12217528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com