If you're taking two characters and turning them into the represented integer value, there's more to it than simply adding the two characters together:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
int main()
{
string code;
cout << "Enter a code: ";
if (cin >> code) {
vector<int> decoded;
for (string::size_type i = 0; i < code.size(); i++) {
int value = code[i] - '0';
if (++i < code.size())
value = 10 * value + (code[i] - '0');
decoded.push_back(value);
}
copy(decoded.begin(), decoded.end(), ostream_iterator<int>(cout, "\n"));
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
You could use a map to help decode the message.
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, char> cipher;
cipher["45"] = 'd';
cipher["32"] = 'o';
cipher["34"] = 'v';
cipher["56"] = 'e';
string encoded = "45323456", decoded = "";
for( unsigned int i = 0; i < encoded.length(); i+=2 )
decoded += cipher[encoded.substr(i, 2)];
cout << decoded << endl;
return 0;
}
sfuo
Practically a Master Poster
656 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99
Is there a simpler way to do it? If not, I'll just have to do some major reading, or I may just abandon this hobby project.
If those are your options, I'll go with no, there's not a simpler way to do it. If you choose to do some major reading then you're well suited to programming. If you choose to abandon the project, I'd suggest finding another hobby, because any project worth doing will push your limits. Quitting over so small a matter means you won't accomplish anything.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
You can do it with a bunch of if/else statements like this
#include <iostream>
using namespace std;
int main()
{
string encoded = "45323456", decoded = "", encodedPart;
for( unsigned int i = 0; i < encoded.length(); i+=2 )
{
encodedPart = encoded.substr(i, 2);
if( encodedPart == "45" )
decoded += 'd';
else if( encodedPart == "32" )
decoded += 'o';
else if( encodedPart == "34" )
decoded += 'v';
else if( encodedPart == "56" )
decoded += 'e';
else
; //this does nothing but without it you will get an error since there is nothing
}
cout << decoded << endl;
return 0;
}
I wouldn't really say the map is over your head since just an array but with custom indexes (some languages call them dictionaries because that is pretty much how they are used).
In map<string, char> the index is a string and what gets held at that index is a char.
Its almost exactly the same as if you had an array of characters except for it is indexed by a string and it is a dynamic array rather than a static one.
sfuo
Practically a Master Poster
656 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99