Reputation: 65
I am working on a project for school and I am asked to input a string and it will convert the string to "leet speak". In my program I take the user input and then pass it to a method that searches an array for each character in the string. When it finds the character it replaces it with the appropriate character from a second array. I am having an issue related to the size of my array and the user input.
#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);
}
It produces the error: terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::replace: __pos (which is 116) > this->size() (which is 4)
Upvotes: 0
Views: 1239
Reputation: 6647
On you line:
input.replace(input[j],1,leetLetters[i]);
The signature for replace
is str.replace(size::t pos, size::t count, string str2)
pos
is the index number of character in your string where you want to start replacing. And right now you are passing in the first char
from input
, which is probably 't'
. 't'
would be converted to number 116
, which is way larger than the size of your string, which is why it throws out of range.
So if you want to replace the first letter to the corresponding string, you would do:
input.replace(j, 1, leetLetters[i]);
About the problem that your function stop in the middle is because your first for
loop for (int j = 0; j < length; j++)
.
Note that in here length
never changed, even you might have actually changed the length of your input
. For instance, if there's a 'w'
in your input, then it will be changed to "\/\/"
, which adds 3 more char
into your input
. So if your input was "what"
, your length would be 4
. After changing 'w'
, it would become "\/\/hat"
. Your function only replace till the length
th character, so "hat"
would remain unchanged.
Instead what you could do is just past in input.length()
in the for loop, so it would be:
for (int j = 0; j < input.length(); j++)
Also note this only work if you replacement letters does not overlap with your normal letters, if they do overlap, you would want to add an increment to j
inside the function by leetLetters[i].length() - 1
, so you would add j += leetLetters[i].length() - 1
inside the function.
Upvotes: 1