[英]Is writing to a file using std::ofstream slower than using std::cout and then redirecting that output to a log file
[英]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.