簡體   English   中英

使用 std::cout 寫入文件時額外的 output

[英]Extra output when writing to file using std::cout

我正在嘗試從文件in.txt讀取數據,經過一些計算,我將 output 寫入out.txt

為什么在out.txt的末尾有一個額外的 7 ?

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;
    }
};

main內容 function。

假設所有標題都包括在內。 findComplement翻轉數字的位。 例如,integer 5 在二進制中是“101”,其補碼是“010”,即 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;
}

in.txt的內容

5
1
1000
120

out.txt的內容

2
0
23
7
7

有一個額外的 7 的原因是您的循環執行了太多次。 嘗試讀取輸入,您需要檢查std::cin

照原樣,您只需重復最后一個測試用例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM