Convert a string to a decimal base C++

user2059300 picture user2059300 · Sep 2, 2013 · Viewed 7.5k times · Source

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.)

Answer

Some programmer dude picture Some programmer dude · Sep 2, 2013

If you want to convert every character in the string to its ASCII equivalent (which seems to be what you want) then you have to iterate over the string and simply take each characters as a number.

If you have a compiler that have range-based for loops then simply do

for (const char& ch : msg)
{
    std::cout << "Character '" << ch << "' is the same as "
              << static_cast<int>(ch) << '\n';
}

If you have an older compiler, then use normal iterators:

for (std::string::const_iterator itr = msg.begin();
     itr != msg.end();
     ++itr)
{
    std::cout << "Character '" << *itr << "' is the same as "
              << static_cast<int>(*itr) << '\n';
}