gpt4 book ai didi

c++ - 从文件读取导致无限循环的问题

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:35 24 4
gpt4 key购买 nike

好的,我正在处理的这个程序似乎一切正常,只是有一个问题。这是代码

#include <iostream>
#include <fstream>

using namespace std;

/*
Function Name: CalculateBinary
CalculateBinary takes a number from the main function and finds its binary form.
*/

void CalculateBinary( long InputNum)
{
//Takes InputNum and divides it down to "1" or "0" so that it can be put in binary form.
if ( InputNum != 1 && InputNum != 0)
CalculateBinary(InputNum/2);

// If the number has no remainder it outputs a "0". Otherwise it outputs a "1".
if (InputNum % 2 == 0)
cout << "0";
else
cout << "1";
}


void main()
{
// Where the current number will be stored
long InputNum;

//Opens the text file and inputs first number into InputNum.
ifstream fin("binin.txt");
fin >> InputNum;

// While Input number is not 0 the loop will continue to evaluate, getting a new number each time.
while (InputNum >= 0)
{
if(InputNum > 1000000000)
cout << "Number too large for this program ....";
else
CalculateBinary(InputNum);

cout << endl;
fin >> InputNum;
}
}

这是我正在阅读的文本文件

12
8764
2147483648
2
-1

当我到达 8764 时,它只是一遍又一遍地读取这个数字。它忽略了 2147483648。我知道我可以通过将 InputNum 声明为 long long 来解决这个问题。但我想知道它为什么要这样做?

最佳答案

这是您编写的此类循环的常见问题。

正确且惯用的循环是这样的:

ifstream fin("binin.txt");
long InputNum;
while (fin >> InputNum && InputNum >= 0)
{
//now construct the logic accordingly!
if(InputNum > 1000000000)
cout << "Number too large for this program ....";
else
CalculateBinary(InputNum);
cout << endl;
}

关于c++ - 从文件读取导致无限循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7405608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com