So I'm to take a message (msg) and convert it to all numbers using the decimal base (A=65, B=66 etc.)
So far, I took the message and have it saved as a string, and am trying to convert it to the decimal base by using a string stream. Is this the right way to go about doing this or is there an easier/more efficient way?
Here is what I have:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string msg;
int P;
cout << "Enter a something: ";
cin >> P;
cout << "Enter your message: ";
cin.ignore( 256, '\n');
getline( cin, msg );
cout << endl << "Message Reads: " << msg << endl ;
int emsg; // To store converted string
stringstream stream; // To perform conversions
stream << msg ; // Load the string
stream >> dec >> emsg; // Extract the integer
cout << "Integer value: " << emsg << endl;
stream.str(""); // Empty the contents
stream.clear(); // Empty the bit flags
return 0;
}
Example Run:
Enter a something: 3 // This is used just to make things go smoothly
Enter your message: This is a message // The message I would like converted to decimal base
Message Reads: This is a message // The ascii message as typed above
Integer value: 0 // I would ultimately like this to be the decimal base message( Ex: 84104105 ...etc.)
You don't need to use stringstream, its much easier than that, just cast to unsigned char (in case you have any chars with a negative encoding) and then to int.
Every character is encoded by an integer, which just happens to be the integer you want. So you can do the conversion with a simple cast.