Десятичная к шестнадцатеричной программе

В настоящее время я работаю над программой для преобразования десятичного ввода в его шестнадцатеричный эквивалент. Я планирую использовать вектор, чтобы систематически собирать значения, а затем выплевывать их в обратном порядке (таким образом, в гексах). Однако я столкнулся с многочисленными проблемами. Все входы до 16 работают как задумано, тогда все становится странным. Ввод 16 приводит к тому, что система выводит смайлик, а 18 — к двум смайликам разного цвета, а 23 — к системному звуковому сигналу.

Это должен быть относительно простой код, он просто действует так, как я никогда не видел! Надеюсь, эта информация поможет

РЕДАКТИРОВАТЬ: я знаю о функции std :: hex, хотя это для класса, и нам не разрешено использовать его к сожалению.

#include <iostream>
#include <string>
#include <vector>
#include <iomanip>

using  namespace std;

int main(){

int input, tester = 0, switchStuff, county = 0, remainderCount = 1, inputCount, remainder = 1, remainderCount2, inputCount2;
string stopGo;
char remainderLetter;

do{

while (tester != 1){
cout << "Enter the number you would like to convert to Hex format: ";
cin >> input;
if (cin.fail()){                     //check if user input is valid
cout << "Error: that is not a valid integer.\n";
cin.clear(); cin.ignore(INT_MAX, '\n');     //Clear input buffer
continue;  //continue skips to top of loop if user input is invalid, allowing another attempt
}
else{
tester = 1;     //Tester variable allows loop to end when good value input
}
}

inputCount = input;

while(inputCount != 0){

remainderCount = inputCount % 16;
inputCount = (inputCount - remainderCount) / 16;
county++;

}

vector<string>userInfo(county);

inputCount2 = input;

for (int i = 0; county > i; i++){

remainderCount2 = inputCount2 % 16;
inputCount2 = (inputCount2 - remainderCount2) / 16;

if (remainderCount2 == 10){
remainderLetter = 'A';
}
else if (remainderCount2 == 11){
remainderLetter = 'B';
}
if (remainderCount2 == 12){
remainderLetter = 'C';
}
else if (remainderCount2 == 13){
remainderLetter = 'D';
}
if (remainderCount2 == 14){
remainderLetter = 'E';
}
else if (remainderCount2 == 15){
remainderLetter = 'F';
}

if (remainderCount2 >= 10){
userInfo[i] = remainderLetter;
}
else{
userInfo[i] = remainderCount2;
}}

cout << "The result in Hexadecimal format is: ";

for (int i = 0; i < county; i++)
cout << userInfo[i];

cout << endl << "Would you like to continue? (Enter Yes/No): ";     //Check whether to continue or not
cin >> stopGo;
cout << endl;

tester = 0;

}while ((stopGo.compare("Yes") == 0) || (stopGo.compare("yes") == 0) || (stopGo.compare("y") == 0) || (stopGo.compare("Y") == 0));   //Leaves user with a range of ways to say 'yes'

cout << "Thank you for using this program!" << endl;

system("pause");
}

0

Решение

Попробуй поменять

userInfo[i] = remainderCount2;

в

userInfo[i] = remainderCount2 + '0';

(‘потому что цифра 0,1, … не совпадает с char’ 0 ‘,’ 1 ‘, …)

Кстати, есть простой способ конвертировать dec в hex

std::string sDecimal[] = "155";
char xHex[50];
sprintf(xHex, "%X", atoi(sDecimal.c_str()));
0

Другие решения