使用 char* 时已弃用的 strcpy/strcat 的替换
Replacements for deprecated strcpy/strcat when using char*
我有 'zombie translator' 的代码作为我教授的示例。据我所知,它需要一串英文单词,并通过函数对其应用一些规则。它目前使用 strcpy
和 strcat
来执行此操作,但是即使我将它们更改为 strcpy_s
,它也不会编译。不包括其他功能(为了space),这里以我的主要功能为例
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 变量更改为字符串或类似的东西?我一直在四处寻找一段时间,找不到实际的过程。
非常感谢您的帮助,非常感谢您的宝贵时间。
来自微软:strncat_s
您需要包括数组的长度以防止缓冲区溢出的危险。
API是:
errno_t strncat_s(
char *strDest,
size_t numberOfElements,
const char *strSource,
size_t count
);
numberOfElements
是目标数组的大小。
我有 'zombie translator' 的代码作为我教授的示例。据我所知,它需要一串英文单词,并通过函数对其应用一些规则。它目前使用 strcpy
和 strcat
来执行此操作,但是即使我将它们更改为 strcpy_s
,它也不会编译。不包括其他功能(为了space),这里以我的主要功能为例
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 变量更改为字符串或类似的东西?我一直在四处寻找一段时间,找不到实际的过程。 非常感谢您的帮助,非常感谢您的宝贵时间。
来自微软:strncat_s
您需要包括数组的长度以防止缓冲区溢出的危险。
API是:
errno_t strncat_s(
char *strDest,
size_t numberOfElements,
const char *strSource,
size_t count
);
numberOfElements
是目标数组的大小。