好的這個程序我工作似乎沒有問題,除了有問題。下面是代碼從文件讀取導致無限循環的問題
#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來解決這個問題。但我想知道它爲什麼這樣做?
是2147483648之前的空間應該在那裏? –
看起來很熟悉:http://stackoverflow.com/questions/7397034/infinite-loop-problem – Mysticial
取決於來自binin.txt的輸入這個程序可能有UB。 – wilhelmtell