gpt4 book ai didi

c++ - 为什么我会在这里得到 out_of_range 异常?

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

目前在 uni 做一个项目,起初我需要取消字符串的连字符,看起来很简单但是当我运行程序时它有一个错误 WeirdPuncProgram.exe: Microsoft C++ exception: std::out_of_range at内存位置 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

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

关于c++ - 为什么我会在这里得到 out_of_range 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34875532/

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