[英]Problem with reading from file causing infinite loop
好的,我正在开发的程序似乎还可以,除非有问题。 这是代码
#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;
}
这个数字太大了long
储存,所以fin >> InputNum;
什么也没做。 您应该始终将其读为while(fin >> InputNum) { ... }
,因为那样一来,它将在失败时立即终止循环,或者至少检查流的状态。
看来您平台上的long
类型为32位宽。 数字2147483648(0x80000000)太大而无法表示为带符号的32位整数。 您要么需要一个无符号类型(显然不适用于负数),要么需要一个64位整数。
另外,您应该检查读取是否成功:
...
cout << endl;
if (!(fin >> InputNum)) break; // break or otherwise handle the error condition
}
您无需检查EOF,因此会永远陷入循环。 fin >> InputNum
表达式如果成功则返回true
,否则返回false
,因此将您的代码更改为如下所示将解决问题:
while ((fin >> InputNum) && InputNum >= 0)
{
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.