从文件读取导致无限循环的问题 [英] Problem with reading from file causing infinite loop
本文介绍了从文件读取导致无限循环的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
确定这个程序我正在工作似乎一切正常,除了有一个问题。这是代码
Ok this program I am working on seems to be all ok except there is a problem. Here is the code
#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;
}
}
这是我正在阅读的文本文件
Here is the text file I am reading in
12
8764
2147483648
2
-1
当我到达8764,它只是继续读这个数字一遍又一遍。它忽略了2147483648.我知道我可以通过声明InputNum为long long解决这个问题。但是我想知道为什么要这样做。
When I get to 8764, it just keeps reading in this number over and over again. It ignores the 2147483648. I know I can solve this by declaring InputNum as a long long. But I want to know why is it doing this?
推荐答案
这是你写的循环的常见问题。
That is the usual problem with such loops which you've written.
正确的和惯用的循环是:
The correct and the idiomatic loop is this:
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;
}
这篇关于从文件读取导致无限循环的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文