2. Write a command line C++ program that will read from a file a number in any b
ID: 3590484 • Letter: 2
Question
Explanation / Answer
#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
//To get int value from char
int val(char c)
{
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10;//to get hex equivalent decimals
}
//To convert integral values to decimal (base 10)
double toDecimal(int b,char *v){
int len = strlen(v);
int power = 1;
int num = 0;
int i;
//from end to begining
for (i = len - 1; i >= 0; i--)
{
if (val(v[i]) >= b)
{
cout<<"Invalid Number"<<endl;
return -1;
}
num += val(v[i]) * power; //convertion of one digit to decimal and adding to result
power = power * b; //incrementing power of base
}
return num;
}
//to convert fraction values to decimal (base 10)
double fracToDecimal(int b,char *v){
int len = strlen(v);
double power = b;
double num = 0;
int i;
//from begining to end
for (i = 0; i <len; i++)
{
if (val(v[i]) >= b)
{
cout<<"Invalid Number"<<endl;
return -1;
}
num += val(v[i]) / power; //convertion of one digit to decimal and adding to result
power = power * b; //incrementing power of base
}
return num;
}
int main()
{
int N;
std::ifstream inputfile("input.txt", std::ios_base::in);
ofstream outputfile;
outputfile.open ("output.txt");
inputfile>>N; //input lines
int base;
char value[100]; //array to store value to convert
char integral[100]; //to store integral part of value
char fraction[100]; //to store fractional part of value
double decimalVal;
//read all lines
while(N>0){
fraction[0]='';//initialize to empty string
integral[0]='';//initialize to empty string
inputfile>>base; //base value
inputfile>>value; //value to convert
int i,j,flag=0; //flag to know vlaue contains fractional part or not and i,j to iterate through integral,fractional parts respectively
//get integral part
for(i=0;i<strlen(value);i++){
if(value[i]=='.'){
flag=1;
break;
}
else{
integral[i]=value[i];
}
}
integral[i] = ''; //end of integral string
i++; //increment so no decimal point (.)
//get fractional part
for(j=0;i<strlen(value);i++){
fraction[j]=value[i];
j++;
}
fraction[j]='';//end of fractional part
if(flag==1){
decimalVal = toDecimal(base,integral)+fracToDecimal(base,fraction);
}
else{
decimalVal = toDecimal(base,value);
}
//write into output file
outputfile<<value<<" base "<<base<<" = "<<decimalVal<<" decimal"<<endl;
N--;
}
outputfile.close();
inputfile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.