I have an infinite loop and don't know why

I don't know what i'm doing wrong

Page 1 of 1

4 Replies - 1002 Views - Last Post: 31 January 2009 - 12:38 PM Rate Topic: -----

#1 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

I have an infinite loop and don't know why

Post icon  Posted 31 January 2009 - 12:18 PM

I need help with this piece of code. I have an infinite loop while trying to loop to the end of the file. I don't know why this is happening since i think this code is right and also that the input file is in the same directory
Here is my code.

#include<iostream>
#include<fstream>
using namespace std;

const int NUM_LIMIT = 10000000;

void main ()
{

	long int num = 0;
	ifstream binin;

	binin.open("binin.txt");

	binin >> num;

	while ( !binin.eof() )
	{
		binin >> num;

	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: I have an infinite loop and don't know why

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6996
  • View blog
  • Posts: 14,633
  • Joined: 16-October 07

Re: I have an infinite loop and don't know why

Posted 31 January 2009 - 12:21 PM

You're looping, always grabbing a number. Perhaps the next token isn't?

You're usually safest grabbing a file a string line at a time and parsing that.
Was This Post Helpful? 0
  • +
  • -

#3 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Re: I have an infinite loop and don't know why

Posted 31 January 2009 - 12:24 PM

yes but the input file should only contain ints, so i don't see why this isn't working
Was This Post Helpful? 0
  • +
  • -

#4 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 5078
  • View blog
  • Posts: 13,705
  • Joined: 18-April 07

Re: I have an infinite loop and don't know why

Posted 31 January 2009 - 12:29 PM

baavgai is absolutely right. Grabbing anything but an int in this case is going to cause a problem. Recheck your file and make sure there is nothing in there that can be seen as not a number. Letters, strange characters, etc.

This code has been tested on a file that contains only ints and works fine. Make sure that you also close your file after the loop (good programming practice)

:)
Was This Post Helpful? 1
  • +
  • -

#5 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Re: I have an infinite loop and don't know why

Posted 31 January 2009 - 12:38 PM

Thanks, i rechecked my file and got it to work
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1