c++ - 将字符串转换为十进制 C++

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

最佳答案

你不需要使用 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";

每个字符都由一个整数编码,恰好是您想要的整数。因此,您可以通过简单的转换进行转换。

关于c++ - 将字符串转换为十进制 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18569734/

相关文章:

c# - 在 C# 中将字符串解析为十进制时无法限制小数位数

c++ - fatal error C1852 :is not a valid precompiled header file

c++ - Rcpp 代码使 R 崩溃

ios - iOS 设备上的外语

python - 如何显示带有两位小数的 float ?

C# 将小数安全地转换为 int

c++ - 旋转 4x4 矩阵会导致随时间缩放

c++ - seekp()、seekg()、read() 和 write() 在同一个文件上的问题

c++ - TCHAR 指针初始化

将十六进制数转换为十进制数