Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extra output when writing to file using std::cout

I am trying to read data from a file in.txt, and after some computations, I am writing the output to out.txt

Why is there an extra 7 at the end of out.txt?

Contents of Solution class.

class Solution
{
public:
    int findComplement(int num)
    {
        int powerof2 = 2, temp = num;

        /*
        get number of bits corresponding to the number, and
        find the smallest power of 2 greater than the number.
        */
        while (temp >> 1)
        {
            temp >>= 1;
            powerof2 <<= 1;
        }

        // subtract the number from powerof2 -1
        return powerof2 - 1 - num;
    }
};

Contents of main function.

Assume all headers are included. findComplement flips bits of a number. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int main() {

#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif

    // helper variables
    Solution answer;
    int testcase;

    // read input file, compute answer, and write to output file
    while (std::cin) {
        std::cin >> testcase;
        std::cout << answer.findComplement(testcase) << "\n";
    }
    return 0;
}

Contents of in.txt

5
1
1000
120

Contents of out.txt

2
0
23
7
7

>Solution :

The reason there is an extra 7 is that your loop executes one too many times. You need to check std::cin after you’ve tried to read the input.

As is, you simply repeat the last test case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading