fork download
  1. #include<math.h>
  2. #include<string.h>
  3. #include<string>
  4. #include<iostream>
  5.  
  6. using namespace std;
  7.  
  8. long int convert_base10(char *num, int base)
  9. {
  10. int len, dig;
  11. long int result = 0;
  12. len = strlen(num);
  13. for(int i=0; i<len; i++)
  14. {
  15. if((num[len-i-1] >= 'A') && (num[len-i-1] <= 'F'))
  16. dig = num[len-i-1] - 55;
  17. else
  18. dig = num[len-i-1] - 48;
  19. result += (dig * pow(base, i));
  20. }
  21. return result;
  22. }
  23.  
  24. void convert_basei(long int num, int base, string &result1)
  25. {
  26. bool error = false;
  27. int pos = 6;
  28. char result[7], rem;
  29. // initially storing space on all position
  30. for(int i=0; i<7; i++)
  31. result[i] = ' ';
  32. while(num)
  33. {
  34. if((num % base) >= 10)
  35. rem = (num % base) + 55;
  36. else
  37. rem = (num % base) + 48;
  38. result[pos] = rem;
  39. num /= base;
  40. pos--;
  41. if(pos < 0 && num > 0)
  42. {
  43. error = true;
  44. break;
  45. }
  46.  
  47. }
  48. if(error == true)
  49. result1 = " ERROR";
  50. else
  51. result1 = result;
  52. }
  53.  
  54. int main()
  55. {
  56. std::cout << "About to start..." << std::endl;
  57.  
  58. char num[7];
  59. string result;
  60. int base1, base2;
  61. std::cout << "About to read input..." << std::endl;
  62. while(std::cin>>num>>base1>>base2)
  63. {
  64. std::cout << "Got [" << num << ", " << base1 << ", " << base2 << "]" << std::endl;
  65.  
  66. long int temp = convert_base10(num, base1);
  67. convert_basei(temp, base2, result);
  68. cout<<result<<endl;
  69. }
  70. std::cout << "got no input" << std::endl;
  71. }
  72.  
  73.  
Success #stdin #stdout 0s 2992KB
stdin
1111000  2 10
1111000  2 16
2102101  3 10
2102101  3 15
  12312  4  2
     1A 15  2
1234567 10 16
   ABCD 16 15
stdout
About to start...
About to read input...
Got [1111000, 2, 10]
    120@��4���N���x
Got [1111000, 2, 16]
     78@��4���N���x
Got [2102101, 3, 10]
   1765@��4���N����
Got [2102101, 3, 15]
    7CA@��4���N����
Got [12312, 4, 2]
  ERROR
Got [1A, 15, 2]
  11001@��4���N���
Got [1234567, 10, 16]
 12D687@��4���N�����
Got [ABCD, 16, 15]
   D071@��4���N���ͫ
got no input