将字符串转换为十进制基数C ++

时间:2013-09-02 09:25:01

标签: c++ string decimal stringstream sstream

所以我要接收一条消息(msg)并使用十进制基数将其转换为所有数字(A = 65,B = 66等)

到目前为止,我接收了消息并将其保存为字符串,并尝试使用字符串流将其转换为十进制基数。这是正确的方法吗?还是有更简单/更有效的方式?

这就是我所拥有的:

#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;
}

示例运行:

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

2 个答案:

答案 0 :(得分:1)

如果你想将字符串中的每个字符转换为它的ASCII等价物(这似乎是你想要的),那么你必须遍历字符串并简单地将每个字符作为数字。

如果您的编译器有range-based for loops,那么只需执行

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

如果你有一个较旧的编译器,那么使用普通的迭代器:

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';
}

答案 1 :(得分:1)

你不需要使用stringstream,它比这更容易,只需要转换为unsigned char(如果你有任何带有负编码的字符),然后再转换为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";

每个字符都由一个整数编码,这恰好是你想要的整数。所以你可以通过一个简单的演员来进行转换。