c++ - 输入 30-something 和 -Ex42,输出 30 和 Ex42
问题描述
我不明白我会怎么做。
输入将是:
3
13894
30-something
-Ex42
并且输出需要是:
13894
30
Ex42
主要任务是制作一个将十二进制数转换为十进制格式的函数。我已经弄清楚了那部分,不需要帮助。我基本上已经删除了围绕十二进制转换的所有代码,只包括了我无法弄清楚的东西。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int to_decimal(const string& str);
int main () {
string str; // Initializes string str for input
cin.ignore (256, '\n'); //ignores the 3 from the input
while (getline(cin, str)) {
//runs str through to_decimal and outputs
cout << to_decimal(str) << endl;
}
}
int to_decimal(const string& str) {
int f = 0;
string localString; // Initialize local string variable
//sets local string to the same as inputted string
localString = str; //used for local string erasing
//This is the idea I have been working on and I cant figure it out
for (unsigned x = 0; x < localString.length(); x++) {
f = localString.at(x);
if (isdigit(f)) {
} else if (f == 'E'){
} else if (f == 'e') {
} else if (f == 'X') {
} else if (f == 'x') {
} else if (f == '-') {
} else if (f == ' ') {
} else {
f = localString.length() - x;
localString.erase(x, f);
break;
}
}
}
解决方案
我有点困惑。您说您需要将十二进制数字转换为十进制,但是在您的示例输出中,只有已转换的行Ex
被转换,但30-something
保持 30,就好像它没有被转换一样 - 并且30
在十二进制中是36
十进制的。号码也一样13894
。
假设您真的想将所有行从十二进制转换为十进制,您可以将您的解决方案基于标准库函数std::stoi()
,该函数可以将字符串从大多数数字基数转换为 36。它要求使用大于9
编码的数字按字母顺序排列的字母 -A
到Z
。因此,您需要简单地将 all you 转换x
为a
all you e
to b
。例子:
int to_decimal(const string& str) {
bool foundDigit = false;
std::string transformedString;
for (auto c : str) {
if (std::isdigit(c) || c == 'E' || c =='e' || c == 'X' || c == 'x') {
foundDigit = true;
// If needed, convert the character.
if (c == 'E' || c == 'e') {
c = 'b';
} else if (c == 'X' || c == 'x') {
c = 'a';
}
transformedString += c;
} else if (foundDigit) {
// Skip everything to the end of the line, if we've already found some digits
break;
}
}
return std::stoi(transformedString, 0, 12);
}
推荐阅读
- sql - 将时间戳转置到开始和结束时间戳列
- powerbi - 如何将 Power BI 中的新字段添加到使用 PowerBIIntegration 集成的现有 PowerApp?
- python - 如何在火花中将一个拆分为多个?
- firebase - firebase 实时数据库查询以查找数据
- java - Broadleaf Commerce Embedded Solr 无法使用 root 用户运行
- c++ - !root 和 root!=NULL 有什么区别
- node.js - 从部署在 heroku 上的 react 应用程序发送 axios (api) 请求
- c# - C#反射获取对象列表
- sql - 如何在 Access 中按百分比划分组/数据?
- json - JSON参数文件字符串连接