質問

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.

cout << "Integer value: ";
for (size_t i = 0 ; i < msg.size(); ++i)
    cout << static_cast<int>(static_cast<unsigned char>(msg[i]));
cout << "\n";

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.

他のヒント

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';
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top