I've coded this program to get a number and a base as two inputs, then prints the number in the given base, it does work well when the base is less than 10, but when I enter a base like 16, instead of printing the word "A" for 10, or F for 15, the program prints the ASCII value of the words, but I want the words themselves.
#include <iostream>
using namespace std;
int base(int n, int t);
int main()
{
char ch;
do {
int n=0, t=0;
base(n,t);
cout << "\n\nDo you want to continue?(y/n)";
cin >> ch;
} while (ch=='y');
}
int base(int n, int t)
{
cout << "\nPlease enter the number : ";
cin >> n;
cout << "\nPlease enter the base : ";
cin >> t;
int i=80;
int x[i];
int m=n;
for (i=1; n>=t ;i++)
{
int rem;
rem = n%t;
n = n/t;
if (rem>9)
{
switch (char(rem))
{
case 10 :
rem = 'A';
break;
case 11 :
rem = 'B';
break;
case 12 :
rem = 'C';
break;
case 13 :
rem = 'D';
break;
case 14 :
rem = 'E';
break;
case 15 :
rem = 'F';
break;
}
}
x[i]=rem;
}
cout << "The number " << m << " in base " << t << " is = ";
cout << n;
for (int j=(i-1); j>0; j--)
cout << x[j];
return 0;
}
I know it's because I have declared x[i] as an integer, so that's why it's happening, but I don't know how to fix this problem.
To print an ASCII code as a character, you cast it to char. So, instead of
cout << x[j];
You can do
cout << static_cast<char>(x[j]);
However, you currently leave digits below 10 as a number, which after casting to char would be wrong. You could fix that by adding '0' to rem if it's less than 10.
Another possibility is changing the type of x from int to char; that way, you wouldn't have to cast.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.