0

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

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • If it does not output what it should, what does it output? – darclander Oct 15 '19 at 22:09
  • FYI, the 1st number on each line is not needed. You could simply read a line via `std::getline()`, put it into a `std::istringstream`, and then read digits from the stream until the end-of-stream is reached. – Remy Lebeau Oct 15 '19 at 22:31
  • darclander I added a link with a screenshot of the output – TheRealPines Oct 15 '19 at 22:44
  • You don't reset `binary` or `counter` on each loop. That could throw you off. –  Oct 15 '19 at 22:45
  • Remy Lebeau I am not accustomed to use "std::" so how would this be used. – TheRealPines Oct 15 '19 at 22:46
  • You can use @RemyLebeau to ping them. Otherwise, without the @, it usually doesn't ping the user. –  Oct 15 '19 at 22:48
  • 2
    If the numbers are in binary, the first line is twenty-two – not ten thousand, one hundred and ten, as your code interprets it as. Binary does not mean "any number written with just ones and zeros". – molbdnilo Oct 15 '19 at 23:23
  • 1
    You also need to read [Why is `iostream::eof` inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). – molbdnilo Oct 15 '19 at 23:25
  • 1
    And you're only reading the length of the first number. And the input is bad (`1 1 9 0 ` will not a binary number make). – molbdnilo Oct 15 '19 at 23:28

2 Answers2

0
#include <iostream> // This library is the basic in/out library
#include <fstream> //This library will allow me to use files
#include <string> //This will allow me to use strings
#include <sstream>

using namespace std;

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

    string line;
    while (getline(infile, line))
    {
        istringstream iss(line);
        iss >> numLength;

        int digit, binary = 0;

        for (int i = 0; i < numLength; i++)
        {
            iss >> digit;
            if (digit == 1)
                binary |= (numLength - i - 1));
        }

        cout << binary << endl;
    }

    return 0;
}

Live demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I can see number `9` in the line: `4 1 1 9 0` -- I wonder how your program takes care of that... – lenik Oct 16 '19 at 01:48
  • @lenik it simply skips digits that are not 1, treating them as 0. But it would be trivial to add additional validation of the input to report/act on other digits – Remy Lebeau Oct 16 '19 at 02:59
-1

As you have written, I believe you have spaces in the file, that the file must be plain text (UTF-8) and that you only want to print on the screen, so:

#include <iostream> // This library is the basic in/out library
#include <fstream> //This library will allow me to use files
#include <string> //This will allow me to use strings

using namespace std;

int main() {

    int defineLengthOfnumLenght[2]; //limited to 99, but will not pass 64(bits)
    int lengthOfnumLenghtPosition = 0;
    char isWhat; //to test if is number, space or breakline
    bool firstSpaceOfLine = false; //is true if you found first space in the line
    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
    int numLength;

    infile.open("binary.txt");

    while (!infile.eof()) {
        infile >> isWhat;
        if (isWhat != ' ' && !firstSpaceOfLine) { //if was number, is not end of line and is not second space - define numLength
            defineLengthOfnumLenght[lengthOfnumLenghtPosition++] = isWhat - '0'; // -'0' will convert ASCII to int, because char is int representing on ASCII table
        }
        else if (isWhat == ' ' && !firstSpaceOfLine) { //when reach first space in line
            firstSpaceOfLine = true;
            if (lengthOfnumLenghtPosition == 1) {
                numLength = defineLengthOfnumLenght[0] - '0';
            }
            else if (lengthOfnumLenghtPosition == 2) {
                numLength = ((defineLengthOfnumLenght[0] - '0') * 10) + defineLengthOfnumLenght[1] - '0';
            }
            cout << numLength << " ";
            lengthOfnumLenghtPosition = 0;
        }
        else { //here will read and "cout" binaries
            firstSpaceOfLine = false;
            for (int i = 0; i < numLength; i++) {
                infile >> isWhat;
                if (isWhat == ' ') {
                    i--;
                }
                else if (isWhat == '\n') {
                    i == numLength;
                }
                else {
                    cout << isWhat - '0';
                }
            }
            cout << "\n";
        }
    }
}

Now you should test, and remember every detail of this code for all the next times because character handling happens a lot in programming!

Also, consider to work with real binaries files (by i or o or nothing fstream file ("nameOfFile.txt or .bin or .anything or nothing , ios::binary);, like ofstream file (file.bin, ios::binary);, and then read as file.read((char *)&yourVariable, sizeof(char or short int or what you want)); - note: here, I always use (char *) before variable, even if its and int or unsigned int (it works, but I dont know why).

Giuliano
  • 100
  • 6
  • I said to test it. But ok, I edited it for people who does not know how to undertand and fix any typing erros (that is not the case of the author of the topic because I know he can do it). Thaks a lot for qualifying me! Now is compiling. Enjoy!!! – Giuliano Oct 16 '19 at 01:08
  • @Guillermo Molina Matus, I almost forget: http://www.cplusplus.com/doc/tutorial/files/ - very good tutorial! – Giuliano Oct 16 '19 at 01:22
  • @Shift_Left, I forgot to tag you. – Giuliano Oct 16 '19 at 01:24