从十六进制到十进制,二进制到十进制和八进制到十进制程序c ++

时间:2016-10-31 10:26:14

标签: c++ hex

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

void main() {
    int a, b;
    while (cin >> a) {
        switch (a) {
        case 2: {
            cin >> b;
            std::string s = std::to_string(b);
            int dec = std::stoi(s, nullptr, 2);
            cout << dec << endl;break;
        }
        case 8:
            cin >> b;
            cout << oct <<b<< endl; break;
        case 16:
            std::cin >> std::hex >> b;
            std::cout << b << std::endl;

        }
    }
}

这是我的代码。其中每一个都有效,但是十六分之一。当我使用它一次时,它就不起作用了。

For example if i have an input: 
2 1111
16  F
8 1
it should have an output:
15
15
1

第一个数字是hex / bin / oct,第二个数字是你给的数字。

关于while(cin&gt;&gt; a),它是那样的,因为它应该是无穷无尽的循环,会有很多输入,是的。我猜它不起作用,因为该声明,但我不知道如何解决它。

1 个答案:

答案 0 :(得分:0)

您的代码可以正常使用:http://ideone.com/tBkJ2x如果您收到错误,则表示您的示例输入以外的其他值。如果您提供的价值会给您带来问题,我很乐意与您合作。

顺便说一句,为什么不只是使用stoi呢?例如:

string s;

while(cin >> a) {
    cin >> s;
    cout << stoi(s, nullptr, a) << endl;
}

Live Example

修改

hexoct是粘性的:https://stackoverflow.com/a/1533222/2642059

因此,如果你设置了这个,你还必须取消它。

您需要将cout << oct <<b<< endl更改为cout << oct << b << dec << endlcin >> hex >> b更改为cin >> hex >> b >> dec以便让您的代码正常运行。 (或者最好切换到我上面的代码。)

当您在读取十六进制数字后输入a时,16被翻译为十六进制数字,因此它被解释为:22(十进制)。