问题描述
我正在尝试使用以下代码创建一个函数来执行内置函数 .erase()
在 C++ 中所做的事情:
string delChar(string text,int no_of_ch_to_delete,int starting_point)
{
int Final_Point = starting_point + no_of_ch_to_delete;
for (int i = starting_point; i <= Final_Point; i++)
{
text = text.at(i) = '\0';
}
return text;
}
这给了我一个我无法弄清楚的错误:
Unhandled exception thrown: write access violation.
std::basic_string<char,std::char_traits<char>,std::allocator<char> >::at(...) returned 0xCD9CC6C4.
我该如何纠正?
解决方法
这一行:
text = text.at(i) = '\0';
实际上与
相同text.at(i) = '\0';
text = '\0';
最后一行用单个字符 text
替换字符串 \0
的任何内容。 text
现在有 1
元素,通过 at(i)
进行的任何进一步访问都是越界的。