C++ 在抛出';std::超出范围';用于查找和替换字符串中的单词的程序

C++ 在抛出';std::超出范围';用于查找和替换字符串中的单词的程序,c++,C++,初学者,我在我的程序中遇到了这个错误,这个程序应该在字符串中找到一个单词,然后用你输入的任何单词替换这个单词。当我在str1中输入多个单词时,它会这样说: terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::erase:__pos (which is 18446744074709551615) > this->size() (which is 9) 这是我的

初学者,我在我的程序中遇到了这个错误,这个程序应该在字符串中找到一个单词,然后用你输入的任何单词替换这个单词。当我在str1中输入多个单词时,它会这样说:

terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::erase:__pos (which is 18446744074709551615) > this->size() (which is 9)
这是我的密码:

#include <iostream>
#include <string>

using namespace std;

void findReplace(string& str1,string& str2,string& str3);

int main() 
{
string str1, str2, str3;

cout << "Enter a sentence that you would like to analyze: \n";
cin >> str1;
cin.ignore();
cout << "Enter a word that you would like to search for: \n";
cin >> str2;
cin.ignore();
cout << "Enter a word that would replace the word that was found: \n";
cin >> str3;
cin.ignore();

findReplace(str1,str2,str3);

return 0;
}

void findReplace(string& str1,string& str2,string& str3)
{
  int length= 0;
  int str2len= 0;
  int str3Length = 0;

  length = str1.length();
  str2len = str2.length();
  str3Length = str3.length();
  
  int found = str1.find(str2);

  if ((found!= string::npos))
  {
    cout << str2 << " found at " << found << endl;
  }

  str1.erase(found, str2len);

  str1.replace(found, str3Length, str3 );
  
  cout << str1;

}
#包括
#包括
使用名称空间std;
作废findReplace(字符串和str1、字符串和str2、字符串和str3);
int main()
{
字符串str1、str2、str3;
cout>str1;
cin.ignore();
cout>str2;
cin.ignore();
cout>str3;
cin.ignore();
findReplace(str1、str2、str3);
返回0;
}
void findReplace(字符串和str1、字符串和str2、字符串和str3)
{
整数长度=0;
int str2len=0;
int str3Length=0;
长度=str1.length();
str2len=str2.length();
str3Length=str3.length();
int found=str1.find(str2);
如果((找到!=string::npos))
{

cout错误消息包含两个大提示:basic_string::erase,在调用
erase
时引发异常,而18446744074709551615是
int
中的最大64位无符号,在现代64位系统中匹配

static const size_type npos=-1;

让我们来看看导致调用<代码>擦除< /代码>:

intfound=str1.find(str2);//find str2
如果((找到!=string::npos))
{//找到str2

cout
18446744074709551615
看起来很像您试图删除未找到的位置(又称
npos
)导致崩溃的输入是什么?如果((找到!=string::npos))
如果找到了项,则删除,但这并不能阻止删除和替换未找到的项。将这两条指令移动到
if
的正文中。我将擦除函数和替换函数移动到if语句中,但现在当我在str1中输入两个以上的单词时,它会跳过str2和str3的cin。
cin>>str1;
只能读一个单词。你很可能需要。
cin >> str1;