Home > Back-end >  Extra output when writing to file using std::cout
Extra output when writing to file using std::cout

Time:12-28

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.

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

CodePudding user response:

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.

  • Related