I'm trying to write a program that covert a hexadecimal number to a decimal number, but i don't know what is the error (a logical error) in this program, any help please!
#include<iostream.h>
#include<string.h>
usingnamespace std;
string dec_to_hex(longint num);
int main()
{
longint num ; // the number in dec
cin >> num ;
cout << dec_to_hex(num) ; // the number in hex
return 0 ;
}
string dec_to_hex(longint num)
{
string hex ; // the program will return (hex)
char z ; // z will be added to hex
longint x=num ;
int c ;
for(c=0;x!=0;c++) // c is the number of digits
x/=10 ;
char array[c] ;
for(int i=c-1;num!=0;i--)
{
int mod = num%16 ;
if(mod>=0 && mod<=9)
z=char(mod+48) ;
else
z=char(mod+55) ;
array[i]=z ; // to add the char in it's place in the array
hex.append(array) ; //to add the array digit in the string
num/=16 ;
}
return hex ;
}
Are you writing in C99 or C++?
Your include files and usingnamespace std; implies this is C++.
Line 24: Allocating an array requires a const which can be evaluated at compile time in C++. Allocating an array with a run time value is only valid in C99. As coder777 said, array isn't even needed.
Also, your include files should be simply <iostream> and <string>. The .h suffix is deprecated in C++, although some very old C++ compilers still use the .h suffix.
In your loop at line 28, you're taking hex digits off from the right so you need to insert the hex characters in the from of hex, which is what coder777 suggested. I suggest you post your current code.