I would pull the last bit from the for loop, in fact this is not so, because this is a special case. I also eliminated some other things that seemed unnecessary and fixed the inside of the loop. See if all this makes sense to you.
I pulled out a keymap declaration because it was not used in your example, and we value what is called โminimal working examplesโ here as a way to isolate and discuss issues convincingly.
Please note that I tried to move all the coding work into one function and from the main () function. This frees up the main part for processing the higher-level parts of the program. On the lines that I designated "Decode here", you can call another function that translates a string of numbers into a character, if that is what you are going to do.
I noted a special case and explicitly pulled it out of the for loop, so that everything inside the for loop can be handled the same. This is better than trying to get the for-loop to do everything.
I disagree with the logic that i=j-1 , so I changed this (I experienced this).
I also switched to reading input directly from the command line to test faster.
I added the #include <string> directive at the beginning so that the program compiles.
Streamlining all coding work within a single function has simplified the declaration of functions into a single argument.
I switched the brackets to fit my own understanding of One True Style.
#include <iostream> #include <fstream> #include <string> using namespace std; void encode(string text) { int j=0,i=0; //Declare j here so we can use in special case for(j=0; j<text.size(); j++){ if(text[j] != text[i]){ cout << text.substr(i, ji) << endl; //Decode here i = j; } } cout << text.substr(i,j-1) << endl; //Decode here. Special case } int main(){ string text; getline(cin, text); encode(text, result); return 0; }
source share