gpt4 book ai didi

c++ - 运行时检查失败 #2 - S,Visual Studio C++

转载 作者:行者123 更新时间:2023-11-28 05:40:49 28 4
gpt4 key购买 nike

这是用“%20”替换字符串中所有空格的方法。它通常工作正常,但在执行结束时出现“运行时检查失败#2 - S”时会提示。我的 for 循环有问题吗?

void replaceSpace(char *s) {
int spaces = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == ' ') {
spaces++;
}
}

// new string that includes overwriting space, and two additional chars
int newLen = strlen(s) + spaces * 2;

s[newLen] = '\0';
for (int i = strlen(s) - 1; i >= 0; i--) {
if (s[i] == ' ') {
s[newLen - 1] = '0';
s[newLen - 2] = '2';
s[newLen - 3] = '%';
newLen -= 3;
}
else {
s[newLen - 1] = s[i];
--newLen;
}
}
}




char test[] = "rep lace Spac e";
replaceSpace(test);
cout << test << endl; //rep%20lace%20Spac%20e

编辑:我通过 cpp shell 运行了这个奇怪的是没有任何问题。我会尝试更新 visual studio 2015,然后报告。

edit2:不,同样的错误。

最佳答案

当你定义test

char test[] = "rep lace Spac e";

您定义了一个恰好 16 个字符的数组(不要忘记字符串终止符)。无法扩展数组,这意味着您将超出数组边界,这会导致未定义的行为

当然,解决方案是改用std::string,然后附加

关于c++ - 运行时检查失败 #2 - S,Visual Studio C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37128968/

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