- 1
C++ Experts Please Help
1. Write a program to enter a string and display it and throw an exception when a null character is detected. 2. Write a program to convert both positive and negative decimal numbers into i) binary ii) hexadecimal using a template function PLEASE HELP _/\_
2 Antworten
+ 1
Indrayudh Mandal Show your attempt
+ 1
THIS ONE'S FOR THE SECOND ONE, BUT UNABLE TO CONVERT NEGATIVE NUMBERS!!
#include<iostream>
using namespace std;
template <typename T>
T bconvert(T x)
{
int i,j,a[20];
for(i=0;x>0;i++)
{
a[i]=x%2;
x=x/2;
}
for(j=i-1;j>=0;j--)
{
cout<<a[j];
}
}
template <typename T>
T hconvert(T y)
{
int temp, i = 1, j, r;
char hex[50];
temp = y;
while (temp != 0)
{
r = temp % 16;
if (r < 10)
hex[i++] = r + 48;
else
hex[i++] = r + 55;
temp = temp / 16;
}
for (j = i; j > 0; j--)
cout << hex[j];
}
int main()
{
int n,p;
cout<<"\nEnter your choice.....\n";
cout<<"1.BINARY CONVERSION:\n2.HEXADECIMAL CONVERSION:";
cin>>p;
cout<<"\nEnter the number:";
cin>>n;
if(p==1)
{
cout<<"\nNumber in decimal: "<<n;
cout<<"\nAfter convert the number in binary:";
bconvert(n);
}
else if(p==2)
{
cout<<"\nNumber in decimal: "<<n;
cout<<"\nAfter convert the number in hexadecimal:";
hconvert(n);
}
else
{
cout<<"WRONG INPUT...";
}
return 0;
}