Advertisement
theTANCO

Base Conversion || main.cpp

Feb 16th, 2023 (edited)
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. // Use this program to convert numbers of one base to another base.
  2. // For example, decimal to hexadecimal, or binary to base 36 (0-Z).
  3. // Base can be anything between 2 and 36.
  4. // Convert.cpp https://pastebin.com/c6HBu4rp
  5. // Convert.h https://pastebin.com/39AvSGaj
  6.  
  7. #include <cstdio>
  8. #include <iostream>
  9. #include <string>
  10. #include "Convert.h"
  11.  
  12. using namespace std;
  13.  
  14. void invalidInput();
  15. void checkValue(string &input, int base);
  16. void checkBase(int &base);
  17.  
  18. int main(){
  19.     Convert convert;
  20.     string initNum;
  21.     string newNum;
  22.     int initBase;
  23.     int newBase;
  24.     int bufferNum;
  25.  
  26.     printf("Enter initial base (2-36): ");
  27.     checkBase(initBase);
  28.     printf("\nValid numbers: %s\n", convert.getBase(initBase).c_str());
  29.     printf("Enter initial number: ");
  30.     checkValue(initNum, initBase);
  31.     printf("\nEnter new base (2-36): ");
  32.     checkBase(newBase);
  33.  
  34.     printf("\nBase %d: %s\n", initBase, initNum.c_str());
  35.     if(newBase != initBase){
  36.         bufferNum = convert.tonumber(initNum, initBase);
  37.         printf("Base 10: %d\n", bufferNum);
  38.         if(newBase != 10){
  39.             newNum = convert.tobase(bufferNum, newBase);
  40.             printf("Base: %d: %s\n", newBase, newNum.c_str());
  41.         }
  42.     }
  43.  
  44.     system("PAUSE");
  45.     return 0;
  46. }
  47.  
  48. void invalidInput(){
  49.     printf("Invalid input. Try again: ");
  50.     cin.clear();
  51.     cin.ignore(10000, '\n');
  52. }
  53.  
  54. bool checkBase(string input, int base){
  55.     for(int i = 0; i < input.length(); i++){
  56.         bool isBase = false;
  57.         for(int b = 0; b < base; b++){
  58.             if(input[i] == Convert().getBase(base)[b]){
  59.                 isBase = true;
  60.                 break;
  61.             }
  62.         }
  63.         if(!isBase){
  64.             return false;
  65.         }
  66.     }
  67.     return true;
  68. }
  69.  
  70. void checkValue(string &input, int base){
  71.     while(!(cin >> input && checkBase(input, base))){
  72.         invalidInput();
  73.     }
  74. }
  75.  
  76. void checkBase(int &base){
  77.     while(!(cin >> base && base > 1 && base < 37)){
  78.         invalidInput();
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement