classes and outputting to a file
hey I am trying to write a program that converts decimal to hex, binary etc. I then need to take the info and output to a file. I am using a class and have the couts in my class functions I was wondering if there was a way I could write to the file from the class functions.
Code:
#include <iostream>
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
void binary(int num);
void hex(int num);
void bcd(int num);
int remove();
class converter
{
private:
#define MAXSIZE 12
int bin[MAXSIZE];
int sec[4];
int remainder;
int newValue;
int k;
public:
converter();
void binary(int num);
void hex(int num);
void bcd(int num);
int remove();
};
converter::converter()
{
remainder = 0;
newValue = 0;
k = 0;
}
void converter::binary(int num)//converts to binary from decimal
{
ofstream myfile;
newValue = num;
while(newValue >= 1)
{
remainder = newValue%2;
if (remainder == 0)
{
bin[k] = 0;
k++;
}
else
{
bin[k]= 1;
k++;
}
newValue = newValue/2;
}
for(k; k<8; k++)
{
bin[k]=0;
}
for(k = 7; k>=0; k--)
{
myfile << bin[k] << endl;
}
}
void converter::hex(int num)
{
ofstream myfile;
k = 0;
int temp = 0;
newValue = num;
while(newValue >= 1 )
{
remainder = newValue%16;
bin[k] = remainder;//used to add the remainder into the array
k++;
newValue = newValue/16;
}
for(k; k < 8; k++)//fills up the array to follow the format
{
bin[k] = 0;
}
for(int g = 1; g>=0; g--)
{
temp = bin[g];
cout << setw (40);
if(temp <= 9)//converts to the appropriate letter for hexadecimal.
{
myfile << temp;
}
else if(temp == 10)
{
myfile << "A";
}
else if (temp == 11)
{
myfile << "B";
}
else if (temp == 12)
{
myfile << "C";
}
else if (temp == 13)
{
myfile << "D";
}
else if (temp == 14)
{
myfile << "E";
}
else
{
myfile << "F";
}
}
}
void converter::bcd(int num)
{
int p = 0;
int i = 0;
int k = 0;
ofstream myfile;
newValue = num;
if(num <= 9)
{
bin[k] = 0;
k++;
bin[k] = 0;
k++;
bin[k] = num;
k++;
}
else if(num <100 && num > 9)
{
bin[k] = 0;
k++;
bin[k] = num/10;
p = num%10;
k++;
bin[k]=p/1;
k++;
}
else
{
bin[k] = num/100;
p = num%100;
k++;
bin[k]=p/10;
p = p%10;
k++;
bin[k] = p;
k++;
}
k = 0;
while(k !=3)
{
newValue = bin[k];
k++;
while(newValue >= 1)
{
remainder = newValue%2;
if (remainder == 0) //sends the value into the correct if statement.
{
sec[i] = 0;
}
else
{
sec[i]= 1;
}
i++;
newValue = newValue/2;
}
for(i; i<4; i++)
{
sec[i]= 0;
}
cout << setw (60);
for (i = 3; i >= 0; i--)
{
myfile << sec[i];
}
i = 0;
}
}
int main()
{
int i = 0;
ofstream myfile;
myfile.open ("numbers.txt");
converter a;
cout<< setw (0);
for(i; i < 256; i++)
{
myfile << i << endl;
a.binary(i);//function call
a.hex(i);
a.bcd(i);
}
myfile.close();
cin.get();
return 0;
}