为什么我在这里得到一个out_of_range例外

Why do I get an out_of_range exception here?

本文关键字:out 一个 of 例外 range 在这里 为什么      更新时间:2023-10-16

目前正在uni做一个项目,首先我需要取消连字符,看起来很简单,但是当我运行程序时,它有一个错误WeirdPuncProgram.exe: Microsoft C++ exception: std::out_of_range at memory location 0x004EF898

它也没有正确返回字符串值,在函数内部answer()被更改并删除连字符,但一旦它出来,它只是原始输入。

#include <iostream>
#include <string>
using namespace std;
string answer;
string hyphonRemover(string answer)
{
   string spacer = " ";
   int h;
   for (int i = 0; i < answer.length(); i++)
   {
      h = answer.find_first_of("-");
      answer.replace(h, 1, spacer);
   }
   return answer;
}

int main()
{
   cout << "Type a sentence which contains punctuation and ill remove it for you! " << endl << endl;
   getline(cin, answer);
   hyphonRemover(answer);
   cout << answer << endl;
   system("pause");
   return 0;
}

hyphonRemover()中每次使用answer都是局部变量,而不是您上面定义的全局变量answer

因此,该函数将仅修改其局部变量。