присваивание целочисленных значений элементам массива char

0

Цель программы - преобразовать десятичную в шестнадцатеричную. 1) У меня возникают проблемы с назначением целочисленных значений элементам массива char, как это делается. Im получает символы для численных значений массива. 2) Как инициализировать мой массив пробелами? чтобы избавиться от мусора и старых данных в элементах массива. 3) Может кто-нибудь объяснить, что моя проблема? с целыми числами и символами? 4) Является ли cout частью моей проблемы?

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <math.h>

int main()
{
using namespace std;

// binary declarations
int x, i, z, n, remainder;
int result = 0;
bool loop_cond, remainder_found, octval_found;

// octal declarations
int octalval,octresult,octremainder,temp_octalval;
int octloop_cnt;
bool oct_loop;
octresult = 0;
// hexadecimal declarations
int hexval, hexremainder, temp_hexval;
int hexloop_cnt;
bool hex_loop,hexval_found;
char hexresult[5] = {" "};

cout << "decimal" << "\t" << "binary" << "\t"<< "octal"<<"\t"<<"hexadecimal"<< endl;

for (i = 1; i <= 256; i++){  
hexloop_cnt = 0;
octremainder = 0;
hexval_found = false;
hex_loop = true;
hexloop_cnt = 0;
while (hex_loop != false){

if (hexval_found != true){
    hexval = i / 16;
    hexremainder = i % 16;
}
else {
    temp_hexval  = hexval;
    hexval = hexval / 16;
    hexremainder = temp_hexval % 16;
}


if (hexval == 0){
    switch (hexremainder){
    case 10:
        hexresult[hexloop_cnt] = 'A';
        break;
    case 11:
        hexresult[hexloop_cnt] = 'B';
        break;
    case 12:
        hexresult[hexloop_cnt] = 'C';
        break;
    case 13:
        hexresult[hexloop_cnt] = 'D';
        break;
    case 14:
        hexresult[hexloop_cnt] = 'E';
        break;
    case 15:
        hexresult[hexloop_cnt] = 'F';
        break;
    default:
        hexresult[hexloop_cnt] = (char)hexremainder;
        break;
    }//end switch
    hex_loop = false;
}//end if

if ((hexval < 16) && (hexval > 0)){
    switch (hexremainder){
    case 10:
        hexresult[hexloop_cnt] = 'A';
        break;
    case 11:
        hexresult[hexloop_cnt] = 'B';
        break;
    case 12:
        hexresult[hexloop_cnt] = 'C';
        break;
    case 13:
        hexresult[hexloop_cnt] = 'D';
        break;
    case 14:
        hexresult[hexloop_cnt] = 'E';
        break;
    case 15:
        hexresult[hexloop_cnt] = 'F';
        break;
    default:
        hexresult[hexloop_cnt] = static_cast<char>(hexremainder);
        break;
    }//end switch
    hexloop_cnt++;
    switch (hexval){
    case 10:
        hexresult[hexloop_cnt] = 'A';
        break;
    case 11:
        hexresult[hexloop_cnt] = 'B';
        break;
    case 12:
        hexresult[hexloop_cnt] = 'C';
        break;
    case 13:
        hexresult[hexloop_cnt] = 'D';
        break;
    case 14:
        hexresult[hexloop_cnt] = 'E';
        break;
    case 15:
        hexresult[hexloop_cnt] = 'F';
        break;
    default:
        hexresult[hexloop_cnt] = static_cast<char>(hexval);
        break;
    }//end switch
    hex_loop = false;
  } //end if

if ((hexval >= 16)){
    switch (hexremainder){
    case 10:
        hexresult[hexloop_cnt] = 'A';
        break;
    case 11:
        hexresult[hexloop_cnt] = 'B';
        break;
    case 12:
        hexresult[hexloop_cnt] = 'C';
        break;
    case 13:
        hexresult[hexloop_cnt] = 'D';
        break;
    case 14:
        hexresult[hexloop_cnt] = 'E';
        break;
    case 15:
        hexresult[hexloop_cnt] = 'F';
        break;
    default:
        hexresult[hexloop_cnt] = static_cast<char>(hexremainder);
        break;
    }//end switch
    hexval_found = true;
}//end if 

hexloop_cnt++;
} //endwhile


    cout << i << "\t" << result <<"\t" << octresult<<"\t" << hexresult<< endl;
    result = 0;
    octresult = 0;
//      hexresult[5] = { ' ', ' ', ' ', ' ', ' ' };
}



cin.clear();
cin.ignore(255, '/n');
cin.get();

return 0;
}
  • 3
    Пожалуйста, сузьте код до соответствующих частей или, еще лучше, создайте минимальный, полный и проверяемый пример и покажите нам.
  • 2
    Также сделайте отступ кода. +1 Иоахиму!
Теги:
arrays

2 ответа

1

вы не можете это сделать

hexresult[hexloop_cnt] = (char)hexremainder;

вам нужно сделать

hexresult[hexloop_cnt] = hexremainder + '0';

Зачем? Хорошо подумайте, если hexremainder = 1. ascii для символа "1" не равен 0x01, это 0x31. Поэтому вам нужно добавить 0x30 к значению. '0' - 0x30 (посмотрите на таблицу ascii, чтобы увидеть, что происходит http://www.asciitable.com/)

0

std :: cout может быть проблемой. Возьмите этот пример.

#include <iostream>

int main()
{
    unsigned char c = 239;
    std::cout << c << "\n";
    std::cout << static_cast<int>(c) << "\n";

    return 0;
}

Вывод:

./a.out 
�
239

Ещё вопросы

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