简体   繁体   中英

Hex, binary, and oct to dec converter doesn't work properly C++

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

long fromBin(long n)
{
    long factor = 1;
    long total = 0;

    while (n != 0)
    {
        total += (n%10) * factor;
        n /= 10;
        factor *= 2;
    }

    return total;
}

int main() {
    int a,b;
    while (true) {
        cin>>a;
        if(a==2){
            cin>>b;
            cout<<fromBin(b)<<endl;
        }
        if(a==16){
            cin >> hex >> b;
            cout << b << endl;
        }
        if(a==8){
            cin>>b;
            cout<<oct<<b<<endl;
        }
    }
}

So my task is pretty simple, but for some reason it doesn't work.I have to 2 numbers in the input.The first one shows what base i want the number (16,2,8) to convert to decimal and the second number is the number.My examples in task are: 2 1111;16 F;8 1 ;and the answers should be 15,15,1 . Also you will that it must be an endless cycle, because how my teacher checks is with examples he has, and he wants from us to be endless cycle.I get the right answers, but only i if i enter the numbers once, the second time something goes wrong and i don't get what is it.For example: when i enter 16 f, i get 15, but when i try to enter it again there is no output and when i try to enter 2 1111, i get 65 for no apparent reason.Another example is when i enter 8 1 and i get 1(which is the correct answer) then i enter 2 1111 and get 17.Again wrong.Whatever i do i can't enter 2 in a row 16 f, the second one doesn't give me an answer.So can you help me?

You change the state of cin and cout with hex and oct , but then you don't set them back when you're done, so on the next pass, it does the wrong thing. Also, you have no code to exit on any kind of error, so your code goes nuts when anyone tries to quit out.

Here it is fixed:

int main() {
    int a,b;
    while (!cin.fail()) // stop after an error
    {
        cin>>a;
        if(a==2){
            cin>>b;
            cout<<fromBin(b)<<endl;
        }
        if(a==16){
            cin >> hex >> b;
            cin >> dec; // put it back the way we found it
            cout << b << endl;
        }
        if(a==8){
            cin>>b;
            cout<<oct<<b<<endl;
            cout<<dec; // put it back the way we found it
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM