Hello so I have this problem/homework for uni and it's due today and I am completely stuck.
It says: Write a program which transforms from base 10 to base 16 integer+ numbers of max 9 numbers. The number in base 10 will be read from the keyboard and the result will be written in a file with the name HEXA.OUT which will contain on the first row the number in base 10 and on the second one the number in base 16.
Can someone help me with this asap I would really appreciat it^^
I guess, your teacher wants that you make the converting by hand and without the help of converting tools.
Also, it seems that you have still problems of correct using the streams library.
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
std::string convert( unsignedlonglong num, unsigned base )
{
if (base < 2 || base > 16) return"Unsupported base!";
if (num == 0) return"0";
std::string result;
while (num)
{
int digit = num % base;
num = num / base;
switch (digit)
{
case 0: case 1: case 2: case 3: case 4:
case 5: case 6: case 7: case 8: case 9:
result = std::to_string(digit) + result;
break;
case 10:
result = "A" + result;
break;
case 11:
result = "B" + result;
break;
case 12:
result = "C" + result;
break;
case 13:
result = "D" + result;
break;
case 14:
result = "E" + result;
break;
case 15:
result = "F" + result;
break;
}
}
return result;
}
unsignedlonglong read_number()
{
unsignedlonglong num;
std::string tmp;
while (true)
{
std::getline( std::cin, tmp);
try { num = std::stoull( tmp ); }
catch (std::exception & e) { continue; }
break;
}
return num;
}
int main()
{
std::string filename = "HEXA.OUT";
std::ofstream ofstr( filename );
unsignedlonglong number;
while (true)
{
std::cout << "Enter a number between 0 and 10000000000\n";
number = read_number();
if ( number < 10000000000 ) break;
}
ofstr << number << '\n';
ofstr << convert(number, 16);
}
you are working way too hard. Stop and think about the math. Peel off one hex digit at a time, same as you would in base 10 (1234 .. mod 10 is 4, /10 is 123, repeat, 3 and 12, ... then you have it in reverse 4321 and just print in reverse... same thing works in hex). 4 lines (while to reverse). 5 if you count the constant lookup table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
unsignedint i = 123456;
string s;
char c[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(i)
{
s+= (char)c[i%16];
i/=16;
}
reverse(s.begin(),s.end());
cout << s << endl;
return 0;
}
you can make it even smaller if you use recursion to reverse it.