In C++ I wanted to make an encode and decode function that is like this:
"AB" encoded is 65S66S. The encode function works as expected, but decode function is not working well.
I tried:
#include <iostream>
#include <string>
using namespace std;
string encodedText;
string decodeTemp;
string decodedText;
string encode (string toEncode)
{
for (int i = 0; i < toEncode.length(); i++)
{
for (int j = 10; j < 126; j++)
{
char test = j;
if (test == toEncode[i])
{
encodedText += to_string(j) + 'S';
break;
};
};
};
return encodedText;
};
string decode (string toDecode)
{
for (int i = 0; i < toDecode.length(); i++)
{
if (toDecode[i] == 'S') {
char test = stoi(decodeTemp);
decodedText += to_string(test);
decodeTemp = "";
continue;
} else { decodeTemp += to_string(toDecode[i]); };
};
/*
Comment to try to fix it:
encodedtext = 65S66S
6 != S, decodeTemp = 6
5 != S, decodeTemp = 65
S == S, decodedText = A
6 != S, decodeTemp = 6
6 != S, decodeTemp = 66
S == S. decodedText = AB
*/
return decodedText;
};
int main ()
{
string myString = "AB";
cout << "Encoded: " << encode(myString) << endl;
cout << "Decoded: " << decode(encode(myString));
return 0;
};
I expected:
Encoded: 65S66S
Decoded: AB
I got:
Encoded: 65S66S
Decoded: 778778
I don't know what went wrong, but it won't work.
S
, and thus seemlessly process the string.
The usage ofstd::istringstream
and std::getline
accomplishes this.The decode
function will then look like this:
#include <sstream>
#include <string>
std::string decode(std::string toDecode)
{
std::string decodedText;
// Create the stream object
std::istringstream strm(toDecode);
std::string sNum;
// each input "line" is terminated with an 'S'
while (std::getline(strm, sNum, 'S'))
{
// Convert the string to a number that will be the ASCII value
decodedText += std::stoi(sNum);
}
return decodedText;
}