【问题标题】:Creating a self-made replica of the erase() function in C++在 C++ 中创建擦除()函数的自制副本
【发布时间】:2021-05-29 04:59:12
【问题描述】:

我正在尝试使用以下代码创建一个函数来执行内置函数 .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'; 为什么要将at 返回的值分配给text

标签: c++ string function runtime-error erase


【解决方案1】:

这一行:

text = text.at(i) = '\0';

实际上与

相同
text.at(i) = '\0';
text = '\0';

最后一行将字符串text 的任何内容替换为单个字符\0text 现在有 1 元素,并且通过 at(i) 进行的任何进一步访问都是越界的。

【讨论】:

  • 声明一个单独的变量来存储缩短的字符串确实消除了错误但没有给出所需的输出,这是为什么呢?
  • @solopolo 您需要查看std::string 的实际工作方式。 std::string 可以在中间包含 \0s,你不能像那样“调整”std::string 的大小
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 2012-05-16
相关资源
最近更新 更多