Десятичная к шестнадцатеричной программе, действующей вверх

0

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

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

EDIT: Я знаю о std :: hex функции, хотя это для класса, и нам не разрешено использовать его unfortunatley.

#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");
 }
  • 1
    Знаете ли вы, что вы можете использовать std :: hex для печати любого целого числа в виде шестнадцатеричного на std :: out?
  • 1
    Может быть, вы подумаете о переключении на что-то вроде этого: cout << hex << numberToConvert; numberToConvert - число в десятичном формате, которое вы хотите преобразовать. Будет сделано то же самое, вы просто измените формат выходных данных.
Показать ещё 1 комментарий
Теги:
vector

1 ответ

0

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

userInfo[i] = remainderCount2;

в

userInfo[i] = remainderCount2 + '0';

("цифра 0,1,... не совпадает с символом" 0 "," 1 ",...)

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

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню