I am trying to make a code that does run=length encoding based on the value entered by the user. Only accepts lower-case letters. Using two vectors. The problem is it doesn't read the last letter of the string. Example: eeeaaaad output: 3e4a (doesn't read d)
What could be the problem?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool is_small_letter(char c){
return c >= 'a' && c <= 'z';
}
void runLength(string str, vector<char>& charachters, vector<int>& length) {
int count;
int i;
for (i = 0; i < str.size() - 1; i++) {
if (!is_small_letter(str.at(i))) {
throw runtime_error("invalid input");
}
count = 1;
while (str.at(i) == str.at(i + 1)) {
count++, i++;
}
if (i == str.size() -1) {
}
charachters.push_back(str.at(i));
length.push_back(count);
}
}
int main() {
string str;
vector<char>charachters;
vector<int>length;
cout << "Enter the data to be compressed: ";
cin >> str;
try {
runLength(str, charachters, length);
cout << "The compressed data is: ";
for (int i = 0; i <= length.size() -1; i++){
cout << length.at(i) << charachters.at(i);
}
} catch (runtime_error &excpt) {
cout << endl << "error: " << excpt.what();
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire