I have an assignment where I am giving a file containing numbers:
5 1 0 1 1 0
4 1 1 9 0
7 1 1 1 0 1 0 1
10 1 0 1 1 1 0 0 0 1 0
The first numbers (5,4,7 & 10) are there to tell how many digits the binary number should have. Then the numbers after that have to be combined since they have spaces in between.
I know that it would be better if they didn't have spaces but the assignment requires spaces.
My code takes in the fist number which I named numLength
to then figure out how many digits the binary value should have. Then it takes in each digit at a time and raises it to the appropriate power so that theoretically when they are all added it should equal the binary number.
For example, 1 0 1 1 0
is turned into 10000 + 0 + 100 + 10 + 0
which equals 10110
This should be happen as there is a binary value on the file.
When I run my program it does not output what it should.
Any suggestions on how I can improve my code to make it do what I want it to do?
#include <iostream> // This library is the basic in/out library
#include <cmath> //This library allows us to use mathematical commands
#include <fstream> //This library will allow me to use files
#include <string> //This will allow me to use strings
using namespace std;
int convertBinaryToDecimal(int);
int combine(int);
int main()
{
ifstream infile; //I am renaming the ifstream command to infile since it is easier to remember and us
ofstream outfile; //I also renamed the ofstream to outfile
infile.open("binary.txt"); //This is opening the binary.txt file which has to be located on the master directory
int numLength; //This will determine how many digits the binary number will have
infile >> numLength;
int digits, binary = 0, DECIMAL;
int counter = numLength - 1;
while (!infile.eof())
{
infile >> digits;
for (int i = 0; i < numLength; i++)
{
binary = binary + (pow(10, counter) * digits);
counter = counter - 1;
infile >> digits;
}
cout << binary << endl;
//DECIMAL = convertBinaryToDecimal(digits);
//cout << DECIMAL;
infile >> numLength;
}
return 0;
}
When I run my program I get this