For this assignment your program must read in data from an i
Solution
#include<iostream>
 #include <fstream>
 using namespace std;
 bool checkBase(int num, int base);
 int convert2To10(int num);
 int convert10To2(int num);
 int main()
 {
 ifstream fin; //Read file
 ofstream fou; //Write file
 int num, base, base2, base10;
 char underscore;
 bool res;
 fin.open(\"input.txt\"); //Open input.txt file for reading
 fou.open (\"output.txt\"); //Open output.txt file for writing
 while (!fin.eof()) //Checks end of file
 {
 fin>>num>>underscore>>base; //Reads the first data
 res = checkBase(num, base); //Checks the correct base
 //If base is correct and it is 10 convert it into base 2
 if(res == true && base == 10)
 {
 //Writes to the output.txt file
 fou<<\"\  decimal = \"<<num<<\" binary = \"<<convert10To2(num)<<endl;
 }
 //If base is correct and it is 2 convert it into base 10
 else if (res == true && base == 2)
 {
 //Writes to the output.txt file
 fou<<\"\  binary = \"<<num<<\" decimal = \"<<convert2To10(1001);
 }
 else
 //Incorrect base Error is written onto the file
 fou<<\"\  Wrong base \";
 }
 }
 //Converts base 2 to base 10
 int convert2To10(int num)
 {
 int rem, bin, dec = 0, base = 1;
 bin = num;
 while (num > 0)
 {
 rem = num % 10;
 dec = dec + rem * base;
 base = base * 2;
 num = num / 10;
 }
 return dec;
 }
 //Converts base 10 to base 2
 int convert10To2(int dec)
 {
 int rem, sum = 0, i = 1;
 do
 {
 rem=dec%2;
 sum=sum + (i*rem);
 dec=dec/2;
 i=i*10;
 }while(dec>0);
 return sum;
 }
//Checks for the correct base
 bool checkBase(int no, int ba)
 {
 int f = 0, r;
 if(ba == 2)
 {
 while(no > 0)
 {
 r = no % 10;
 if(r == 0 || r == 1)
 {
 no = no / 10;
 }
 else
 {
 f = 1;
 break;
 }
}
 if(f == 1)
 return false;
 else
 return true;
 }
 if(ba == 10)
 {
 while(no > 0)
 {
 r = no % 10;
 if(r == 0 || r == 1 || r == 2 ||r == 3 ||r == 4 ||r == 5 ||r == 6 ||r == 7 ||r == 8 ||r == 0)
 {
 no = no / 10;
 }
 else
 {
 f = 1;
 break;
 }
 }
 if(f == 1)
 return false;
 else
 return true;
 }
}
Input File:
1001, 2
 1001, 10
 12301, 2
 12801, 10
Output File:
 binary = 1001 decimal = 9
 decimal = 1001 binary = 1111101001
Wrong base
 decimal = 12801 binary = 1588754945


