【问题标题】:Replacements for deprecated strcpy/strcat when using char*使用 char* 时替换已弃用的 strcpy/strcat
【发布时间】:2017-03-02 22:53:32
【问题描述】:

我的教授有一个“僵尸翻译”的代码作为示例。据我所知,它需要一串英文单词并通过函数对其应用一些规则。它目前使用strcpystrcat 来执行此操作,但是即使我将它们更改为strcpy_s,它也不会编译。不包括其他功能(为了篇幅),这里以我的主要功能为例

int main()
{
char english[MAX];
char zombie[MAX];
char zombie_word[MAX];
int pos_e; /* Current position in english line of text */
int pos_z; /* Current position in line of translated zombie text */

while (1) {
    pos_e = 0;
    pos_z = 0;
    strcpy(zombie, "");

    cout << ("Enter English text: ");
    cin >> english;

    /* This loop translates the line from english to zombie. */
    do
    {
        get_next_word(english, &pos_e, zombie, &pos_z);

        translate_word(english, &pos_e, zombie_word, &pos_z);

        strcat(zombie, zombie_word);

    } while (pos_e < strlen(english));

    print_translation(zombie);
}
return 0;
}

更具体地说,我应该如何处理strcat(zombie, zombie_word); 行以使其在 Visual Studio 2015 中正确编译?

不是为了一个成绩,我只是很想在期中之前能看懂这个,玩起来有点难。我宁愿不必通过 _CRT_SECURE_NO_WARNINGS 禁用它,这样我就知道如果我需要做类似的事情该怎么做。

也许将 char 变量更改为字符串或类似的东西?我已经环顾了一段时间,找不到实际的过程。 非常感谢您的帮助,非常感谢您的宝贵时间。

【问题讨论】:

  • 你能分享一下 strcpy_s 的问题吗? c++ 更好的解决方案是 std::string,但您可能还需要知道如何在某个阶段使用 strcpy_s。
  • 在 C++ 中,正确的答案几乎总是将char* 转换为std::string,但是当您将strcat 和朋友替换为_s 版本时只是出于兴趣,出了什么问题?您是否阅读了documentation page 以了解两者之间的区别?
  • 我的错误似乎只存在于其他函数中,我收到消息 strcpy_s 错误:没有重载函数“strcpy_s”的实例与参数列表匹配。
  • 请注意,有一个proposal N1967,C 委员会应该弃用_s 函数并保留原件。 :-)
  • 你不能只是将strcpy 更改为strcpy_s,它们有不同的参数——strcpy_s 要求你将目标缓冲区的大小作为参数 2 传递。

标签: c++ string char strcpy strcat


【解决方案1】:

来自微软:strncat_s

您需要包含数组的长度以防止缓冲区溢出危险。

API 是:

errno_t strncat_s(  
   char *strDest,  
   size_t numberOfElements,  
   const char *strSource,  
   size_t count  
);

numberOfElements 是目标数组的大小。

【讨论】:

  • 不止于此。 strncpy_s 在溢出、截断、崩溃、调用自定义处理程序等方面有一系列附加选项...
  • strncpy_s(zombie, ""); 现在产生错误:没有重载函数“strncpy_s”的实例与参数列表匹配。误会请见谅,需要把数组的长度放在括号里面吗?
猜你喜欢
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 2011-11-26
  • 2021-12-24
相关资源
最近更新 更多