I'm suppose to read a file in(which is in hex), store the data in a 2d array, and write the data in binary to another file. I think that my input and output file are good but I am wondering if I did the print in binary correct with the bitset. I know for sure that my main() function is all screwed up because I am not storing the data correctly. Should I by putting my input function before the creating the 2d array?
#include <fstream>
#include <iostream>
#include <bitset>
usingnamespace std;
// Funtion definitions
void getInput(); // function that gets input file name
void getOutput(); // function that gets output file name
void Printoutput(); // function that prints to output file
// Variable definitions
int rows, cols;
ifstream fin;
ofstream fout;
bool outputToFile = "False";
string outputfile = "output.txt";
string inputfile = "input.txt";
int main()
{
int**data = newint*[rows]; // Creating the array
// getInput(); // function that gets input file
// getOutput(); // function that gets output file
for(int i = 0; i < rows; i++)
data[i] = newint[cols];
getInput();
getOutput();
Printoutput(); // function that prints hex numbers in binary
}
void Printoutput() // Function that prints the data in binary
{
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
{
std::bitset<4> x(j);
std::cout << x;
}
}
void getInput() // function that gets input file name
{
start:;
cout << "Enter a file name: " << endl;
cin >> inputfile >> hex>> data[i][j]; // Puts the hex numbers into an 2d array
fin.open (inputfile.c_str());
if (fin.fail())
{
cout << "The input file cant be opened." << endl;
goto start; // If file fails to open it repeats the question
}
}
void getOutput() // function that gets output file name
{
start:;
cout << "Enter an output file names: " << endl;
cin >> outputfile;
fout.open (outputfile.c_str());
if (fin.fail())
{
cout << "The output file cant be opened." << endl;
goto start; // If file fails to open it repeats the question
}
}
You'll definitely want to get the size of the array you're allocating before you allocate it. Global variables are zero-initialized, so you're are currently allocating an array with 0 elements.
You need a [/code] tag at the end of you code to finish formatting the OP. (Feel free to edit the post and add it.)
At some point you have to determine what the size is that you're allocating. Figure that out before you allocate it.
You can't just say "Oh magical compiler, please read my mind and allocate an array of size X when I tell you to allocate an array with no elements."
Now, it may be that you start out with an array of size 1 and increase the size by allocating a new array and copying the old one to it every time you determine you need another element, but you have to explicitly do this. The compiler cannot do it for you.
Things would be much easier if you used a std::vector.