2011-09-13 72 views
0

好的这个程序我工作似乎没有问题,除了有问题。下面是代码从文件读取导致无限循环的问题

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

+0

是2147483648之前的空间应该在那里? –

+0

看起来很熟悉:http://stackoverflow.com/questions/7397034/infinite-loop-problem – Mysticial

+0

取决于来自binin.txt的输入这个程序可能有UB。 – wilhelmtell

回答

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

立即中止 – pezcode

+0

@pezcode:有一个错字。我想用0, – Nawaz

+0

@Nawaz初始化'InputNum',只是反转while循环条件。 – MSN

0

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

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

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

你不检查EOF,从而陷入一个死循环。 fin >> InputNum表达式返回true如果成功,否则false,所以改变了你的代码这样的事情会解决这个问题:

while ((fin >> InputNum) && InputNum >= 0) 
{ 
    // ... 
} 
2

这个数字太大了long存储,所以fin >> InputNum;什么都不做。您应该始终读为while(fin >> InputNum) { ... },因为这会在故障时立即终止循环,或者至少检查流状态。