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

时间:2016-05-10 03:49:11

标签: c++ runtime

这是用'%20'替换字符串中所有空格的方法。它的工作原理很好,但是在执行完成时会出现'Run-Time Check Failure#2 - S'。我的for循环有问题吗?

tf.save()

编辑:我通过cpp shell运行了这个并没有任何奇怪的问题。生病了尝试更新visual studio 2015,并报告回来。

edit2:不,同样的错误。

2 个答案:

答案 0 :(得分:1)

定义test

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

你定义一个完全 16个字符的数组(不要忘记字符串终止符)。没有办法扩展数组,这意味着你将写出数组的边界,导致未定义的行为

当然,解决方案是使用std::string代替追加

答案 1 :(得分:0)

真的,这段代码不是必需的。检查一下:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main()
{
    std::string s("rep lace Spac e");
    s.erase(std::remove_if(s.begin(), s.end(), static_cast<int(*)(int)>(std::isspace)), s.end());
    std::cout << s;
}