簡體   English   中英

在拋出'std::out_of_range' what() 實例后調用 C++ 終止:basic_string::replace: __pos

[英]C++ terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::replace: __pos

我正在為學校做一個項目,我被要求輸入一個字符串,它會將字符串轉換為“leet speak”。 在我的程序中,我接受用戶輸入,然后將其傳遞給一個方法,該方法為字符串中的每個字符搜索一個數組。 當它找到該字符時,它會用第二個數組中的適當字符替換它。 我遇到了與數組大小和用戶輸入相關的問題。

#include <iostream>
#include <string>
using namespace std;

void leetTranslate(string input) {
  int length = input.length();
  cout << length;
  char normalLetters[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  string leetLetters[26] = {"4","B","(","D","3","Ph","9","|-|","1","j","|<","L","/\\/\\","|\\| ","0","P","Q",
  "R","$","7","U","\\/","\\/\\/","><","'/","Z"};

  for (int j = 0; j < length; j++) {
    for (int i = 0; i < 26; i++) {
      if (input[j] == normalLetters[i]) {
        input.replace(j,1,leetLetters[i]);
      }
    }
  }

  cout << input;
  

}

int main() {
  string userInput;
  cout << "Enter a string: ";
  getline(cin, userInput);

  leetTranslate(userInput);
}

它產生錯誤: terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::replace: __pos (which is 116) > this->size() (which is 4)

在你線上:

input.replace(input[j],1,leetLetters[i]);

replace的簽名是str.replace(size::t pos, size::t count, string str2)

pos是字符串中要開始替換的字符的索引號。 現在您正在從input傳入第一個char ,這可能是't' 't'將轉換為數字116 ,它比字符串的大小大得多,這就是它超出范圍的原因。

因此,如果您想將第一個字母替換為相應的字符串,您可以這樣做:

input.replace(j, 1, leetLetters[i]);

編輯:

關於您的函數停在中間的問題是因為您的第一個for循環for (int j = 0; j < length; j++)

請注意,這里的length從未改變,即使您實際上可能已經更改了input的長度。 例如,如果您的輸入中有一個'w' ,那么它將被更改為"\\/\\/" ,這會在您的input添加 3 個char 因此,如果您的輸入是"what" ,則您的長度將為4 更改'w' ,它將變為"\\/\\/hat" 您的函數僅替換到length th 個字符,因此"hat"將保持不變。

相反,您可以做的只是在 for 循環中的input.length()中過去,所以它將是:

for (int j = 0; j < input.length(); j++)

另請注意,這僅適用於替換字母與普通字母不重疊的情況,如果它們確實重疊,則您希望通過leetLetters[i].length() - 1在函數leetLetters[i].length() - 1 j添加增量,因此您將添加j += leetLetters[i].length() - 1在函數內部。

暫無
暫無

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

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