By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,336 Members | 2,315 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,336 IT Pros & Developers. It's quick & easy.

How to stop a loop before it gets to the last one

P: 16
This loop goes through all the lines in the file but there are only six lines and it has seven outputs
Oct 12 '10 #1
Share this Question
Share on Google+
9 Replies


Oralloy
Expert 100+
P: 983
Well, try using a loop counter in addition to your eof condition:
Expand|Select|Wrap|Line Numbers
  1. int count = 1;
  2. while ( (count < 7) && !cin.eof() )
  3. {
  4.   count ++;
  5. . . .
Oct 12 '10 #2

P: 16
that would work but there could be more or less than 7 in the file.
Oct 12 '10 #3

Oralloy
Expert 100+
P: 983
So what is the alternate terminiation condition?

If you know how to detect the state, you can either detect at the top of the file, or you can insert this code following line 25 of your example:
Expand|Select|Wrap|Line Numbers
  1.      if (cin.eof())
  2.         break;
Luck!
Oct 12 '10 #4

P: 16
Parse error on line 55: break statements are only allowed within switch statements;
breaking out of a loop is not supported.

I added that and it gave me this error.
Oct 12 '10 #5

Oralloy
Expert 100+
P: 983
You're using C#, aren't you?

Ok, so you need to build a guard around the while loop at line 26. You can do it the easy way and write:
Expand|Select|Wrap|Line Numbers
  1.         while ( (!cin.eof()) && (count <= scores_in_section) ) 
Or you can guard the whole thing with an "if" statement:
Expand|Select|Wrap|Line Numbers
  1.         if (!cin.eof())
  2.         {
  3.           while ( count <= scores_in_section ) 
  4.           {
  5.           . . .
  6.           }
  7.         }
  8.  
Oct 12 '10 #6

P: 16
Actually im using C++, but heres the whole code because i think the problem is the first if statement is set to 0at the end and thats why it outputs that seventh one:
Oct 12 '10 #7

Oralloy
Expert 100+
P: 983
After line 37, try inserting
Expand|Select|Wrap|Line Numbers
  1. if (!cin.eof()) {
And after line 106 insert
Expand|Select|Wrap|Line Numbers
  1. }
That should effectively mask out the section logic when EOF occurs on input.
Oct 12 '10 #8

P: 16
Dude thankyou soo much!!! You are awesome
Oct 12 '10 #9

Oralloy
Expert 100+
P: 983
No worries, nuken. Just be sure to help others when you can.

Luck!
Oct 12 '10 #10

Post your reply

Sign in to post your reply or Sign up for a free account.