Strncat& strncpy帮助C ++ [英] strncat & strncpy help c++

查看:91
本文介绍了Strncat& strncpy帮助C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的任务是:


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

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)

连接字符串 a b 到缓冲区结果。确保
不会超出结果。它可以容纳 result_maxlength 个字符,
不计算 \0 终止符。 (也就是说,缓冲区具有
buffer_maxlength + 1 个字节。)请确保提供'\0'
终止符。

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

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);
}


推荐答案


  1. 从a到结果的结果(取较小值,长度为a或result_maxlength)

  2. strncat从b到结果的剩余值(取较小值, b的长度或a的result_maxlength-的长度

  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)

在每次返回之前,仅将position0放在最后一个位置 result [result_maxlength- 1] ='\0';

before every return just put a \0 at last position result[result_maxlength-1] ='\0';

实际上未指定要做什么如果结果太短,是否应添加尾随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.

技巧:结果的剩余部分是 result + strlen(a)

tip : remaining of result is result+strlen(a)

这篇关于Strncat&amp; strncpy帮助C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆