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

时间:2011-09-13 16:58:24

标签: c++ loops infinite

好的,我正在研究的这个程序似乎没问题,除非有问题。这是代码

#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来解决这个问题。但我想知道为什么会这样做?

4 个答案:

答案 0 :(得分:4)

这是你写过的这类循环的常见问题。

正确和惯用的循环是:

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

答案 1 :(得分:2)

这个数字对于long来说太大了,所以fin >> InputNum;什么都不做。您应该始终读为while(fin >> InputNum) { ... },因为它将在失败时立即终止循环,或者至少检查流状态。

答案 2 :(得分:0)

您平台上的long类型似乎是32位宽。数字2147483648(0x80000000)太大而无法表示为带符号的32位整数。您需要一个无符号类型(显然不能使用负数)或64位整数。

此外,您应该检查读取是否成功:

  ...
  cout << endl;
  if (!(fin >> InputNum)) break; // break or otherwise handle the error condition
}

答案 3 :(得分:0)

你没有检查EOF,因此永远被困在一个循环中。 fin >> InputNum表达式如果成功则返回true,否则false,因此将代码更改为此类可以解决问题:

while ((fin >> InputNum) && InputNum >= 0)
{
  // ...
}
相关问题