首页 > 解决方案 > 输入 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;
        }
    }
}

标签: c++

解决方案


我有点困惑。您说您需要将十二进制数字转换为十进制,但是在您的示例输出中,只有已转换的行Ex被转换,但30-something保持 30,就好像它没有被转换一样 - 并且30在十二进制中是36十进制的。号码也一样13894

假设您真的想将所有行从十二进制转换为十进制,您可以将您的解决方案基于标准库函数std::stoi(),该函数可以将字符串从大多数数字基数转换为 36。它要求使用大于9编码的数字按字母顺序排列的字母 -AZ。因此,您需要简单地将 all you 转换xaall you eto 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);
}

推荐阅读