簡體   English   中英

在為我的程序拋出一個 'std::out_of_range' 實例后調用 Terminate 來查找和替換字符串中的單詞

[英]Terminate called after throwing an instance of 'std::out_of_range' for my program which finds and replaces words in a string

初學者,我在我的程序中遇到這個錯誤,它應該在字符串中找到一個單詞,然后用您輸入的任何單詞替換該單詞。 當我在 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;

}

錯誤消息包含兩個重要提示: basic_string::erase ,在調用erase時拋出異常, 18446744074709551615是最大 64 位 unsigned in int ,在現代 64 位系統上與npos的定義匹配

static const size_type npos = -1;

那么讓我們來看看是什么導致了調用erase

  int found = str1.find(str2); // find str2

  if ((found!= string::npos))
  { // found str2
    cout << str2 << " found at " << found << endl; // print that we found it
  }

  str1.erase(found, str2len); // erase it (even if we didn't find it)

  str1.replace(found, str3Length, str3 ); // replace it (even if we didn't find it)

使固定:

  auto found = str1.find(str2); // Note: Position ISN'T an int. auto will 
                                // find and use correct type. If auto's not available
                                // size_t will do the job.

  if ((found!= string::npos))
  { // found str2
    cout << str2 << " found at " << found << endl; // print that we found it
    str1.erase(found, str2len); // erase it 

    str1.replace(found, str3Length, str3 ); // replace it 
  }

此外:

cin >> str1;

只會讀一個字。 既然需要一句話,就 std::getline

您可以丟棄所有cin.ignore() s。 他們在這里沒用。 >>將在標記山雀找到之前消耗任何剩余的空白。 它會在標記后留下空格,所以請注意為什么在格式化提取后 std::getline() 會跳過輸入? 如果在>>之后放置std::getline

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM