将字符串转换为十进制基C++
Convert a string to a decimal base C++
所以我要接收一条消息(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.)
您不需要使用字符串流,它比这容易得多,只需转换为无符号字符(如果您有任何负编码的字符),然后转换为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";
每个字符都由一个整数编码,而这个整数恰好是您想要的整数。因此,您可以使用简单的强制转换来进行转换。
如果您想将字符串中的每个字符转换为ASCII等价字符(这似乎是您想要的),那么您必须对字符串进行迭代,并将每个字符作为一个数字。
如果您的编译器具有基于范围的for
循环,那么只需执行
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';
}
相关文章:
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- 计算十进制 c++ 之后的数字
- C++从二进制转换为十进制数
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- Geeksforgeeks C 程序故障排除:IEE 754 表示法为十进制
- cin 的十进制输入验证?
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 将分数转换为十进制数并对其进行排序
- uint8_t同一二进制文件的不同十进制值
- 如何打印大于"无符号长长"的"std::bitset"的十进制值?
- 调用方如何知道 VARIANT 中何时有十进制?
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 十进制到二进制转换器 c++
- 使用标准库计算字符串中的十进制数
- 如何在C ++中将二进制字符串128位转换为十进制字符串?
- 如何计算整数的十进制数字?
- (第 1 位 + 第 2 位)以十进制数表示
- 在 C++ 中使用带有十六进制十进制和八进制数的 unsetf