0
#include <string>
#include <iostream>

using namespace std;

int main() {
    string input, numBin = ""; 
    cout << "Enter a hexadecimal number: ";
    getline(cin, input);

    for (int i = 0; i < input.length(); i++) {
        switch (input[i]) {
            case 0: numBin.append("0000"); break; 
            case 1: numBin.append("0001"); break;
            case 2: numBin.append("0010"); break;
            case 3: numBin.append("0011"); break;
            case 4: numBin.append("0100"); break;
            case 5: numBin.append("0101"); break;
            case 6: numBin.append("0110"); break;
            case 7: numBin.append("0111"); break; 
            case 8: numBin.append("1000"); break;
            case 9: numBin.append("1001"); break;
            case 'a': numBin.append("1010"); break;
            case 'A': numBin.append("1010"); break;
            case 'b': numBin.append("1011"); break;
            case 'B': numBin.append("1011"); break;
            case 'c': numBin.append("1100"); break;
            case 'C': numBin.append("1100"); break;
            case 'd': numBin.append("1101"); break;
            case 'D': numBin.append("1101"); break;
            case 'e': numBin.append("1110"); break;
            case 'E': numBin.append("1110"); break;
            case 'f': numBin.append("1111"); break;
            case 'F': numBin.append("1111"); break; 
            default: break;
        }
    }
    cout << "Your number in binary is " << numBin << "."; 
}

This program is supposed to change a hexadecimal input ('input') into a binary result ('numBin'). I don't have much experience using switch statements and do not fully understand the "default" case, so any clarification about that or if I am using it incorrectly would be helpful!

The error I'm getting is on the for loop, and it thorws: comparison between signed and unsigned integer expressions [-Wsign-compare]

Joe Walley
  • 21
  • 4

2 Answers2

2
case '0':
case '1':
...

Use all characters..not number and characters.

And one ore thing..for(i=0;i<(int) input.length();i++)

user2736738
  • 30,591
  • 5
  • 42
  • 56
2

In the line:

for (int i = 0; i < input.length(); i++) ...

input.length() returns a size_t, which is a unsigned type. (see http://www.cplusplus.com/reference/string/string/length/)

Comparing signed and unsigned values is not safe, which is why the compiler warns you, read more about it in this post among many others: A warning - comparison between signed and unsigned integer expressions

To fix it, simply change to

unsigned int i = 0

The default switch case will be executed when none of the other cases match. You should put some code there that handles incorrect input for example.

Community
  • 1
  • 1
Unimportant
  • 2,076
  • 14
  • 19