【问题标题】:Extra output when writing to file using std::cout使用 std::cout 写入文件时的额外输出
【发布时间】:2021-12-28 05:04:16
【问题描述】:

我正在尝试从文件in.txt 读取数据,经过一些计算,我将输出写入out.txt

为什么out.txt的末尾多了一个7?

Solution 类的内容。

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 函数的内容。

假设所有标题都包括在内。 findComplement 翻转数字的位。例如,整数 5 在二进制中是“101”,其补码是“010”,即整数 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

【问题讨论】:

    标签: c++ std cin cout freopen


    【解决方案1】:

    有一个额外的 7 的原因是你的循环执行了太多次。您需要检查std::cin您尝试读取输入之后。

    按原样,您只需重复上一个测试用例。

    【讨论】:

    • 哦,我明白了。 while (std::cin &amp;&amp; std::cin &gt;&gt; value) 成功了。虽然我没有完全理解。这是否意味着——如果“stdin 有输入”并且“输入有效”,那么做点什么?
    • @AdityaWagh 你可以写成while (std::cin &gt;&gt; value)。您可以将其“翻译”为“尝试提取一个值,如果提取没有错误,则执行循环体”。
    • 谢谢!那清除它。祝你有美好的一天!
    猜你喜欢
    • 2013-09-11
    • 2021-01-28
    • 2021-05-20
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多