Hi everyone! First of all, I am completely new to programming so I apologize in advance for any major mistakes.
So I've been assigned to write a program that converts decimal to hexadecimal, and the instructions say that I may not use any of the dec or hex format flags provided by iostream or the stoi, stol, stoul,stoll, stoull, stof, stod, and stold functions provided by the string library.
#include <iostream>
#include <string>
usingnamespace std;
int main() {
int num;
int division = 0;
int remainder = 0;
string rem = "";
string hex_num = "";
cout << "Enter a decimal number: " << endl;
cin >> num;
while (division == 0)
{
division = num / 16;
remainder = num % 16;
{
if (remainder > 10) //if remainder is greater than 10
{
char c = static_cast <char>((remainder - 10) + 'A'); // subtract 10 from division and add 'A' (65) to get character in ASCII (A-F)
rem = string(1, c); // convert char into a string of length 1
cout<<rem<<endl;
}
elseif (remainder == 10)//remainder is equal to 10
{
char c = static_cast <char>(17 + '0'); //add 17 to get character 'A'
rem = string(1, c);
cout << rem << endl;
}
else // remainder is less than 10
{
char c = static_cast <char>(remainder + '0'); // Add remainder to '0' (48) to get character in ASCII (0-9)
rem = string(1, c); // convert char into a string of length 1
cout << rem << endl;
}
}
}
hex_num = //string sum of remainder characters
cout << "Your number in hex is 0x" << hex_num << endl;
}
I think it's my while loop that I'm not getting right, and I am also having trouble with coming up with how to concatenate the characters into a string that displays the hexadecimal. Any help/hints would be greatly appreciated. Thanks!
int num;
cout << "Enter a decimal number: " << endl;
cin >> num;
int division = num;
Then the loop condition is while (division != 0)
Some of the other code is more complex than necessary, the code for remainder == 10 can be merged with code for remainder > 10, they both have the same requirements.
To build the final string, you need to concatenate (join) the character c to the string hex_num. Add it to the start, not the end, using the + operator.
@Repeater Yeah at first it didn't make sense to me either. I asked someone else to take a look at my while loop and they suggested to set the condition to division==0, the thought process behind that being if, for example, the user inputs the number 177: