While loop not ending when reading from file

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

While loop not ending when reading from file

 
0
  #1
Jan 20th, 2006
I have a program that reads from a file, but for some reason it never reaches the end of the file or something, because the loop never ends. I put only 2 lines of text in the file, and a loop like this still ran infinite:

  1.  
  2. while (! my_file.eof())


Here is the full code:

Implementation:
  1. //-include the DebitCard implementation
  2. #include "Card.h"
  3. //-include the header for I/O
  4. #include <iostream>
  5. //-include header for files
  6. #include <fstream>
  7. #include <string>
  8. //-using definitions
  9. //-used as a shortcut
  10. using std::cout;
  11. using std::cin;
  12. using std::endl;
  13.  
  14. /**main()
  15.  *-definition of this file
  16.  *-goes in the main method
  17.  *-main method allows the
  18.  *-program to be run
  19.  **/
  20. int main()
  21. {
  22. DebitCard dc;
  23. //-char array for filename
  24. char filename[50];
  25. //-double for read amount
  26. double my_double = 0;
  27. //-char array to hold the information read
  28. char info[50];
  29. //-declaration of file object
  30. ifstream my_file;
  31.  
  32. //-prompt the user
  33. cout << "Enter The File --> ";
  34. //-get the filename from the user
  35. cin.getline(filename, sizeof(filename));
  36. //-open the file based on the input
  37. my_file.open(filename);
  38.  
  39. //-keep count of lines
  40. int count = 1;
  41. //-loop while it's no the end of the file
  42. while (! my_file.eof())
  43. {
  44. //-get the line from file
  45. my_file.getline(info,sizeof(info));
  46. //-store the value in a double
  47. //-this must be converted
  48. my_double = atof(info);
  49. //-if count is one, then we are on
  50. //-the first line and it is the balance
  51. //-to set the debit card to.
  52. if (count == 1)
  53. {
  54. //-print out the balance
  55. cout << "The Starting Balance Was --> " << my_double << endl;
  56. //-set the balance
  57. dc.set_balance(my_double);
  58. }
  59. else
  60. {
  61. //-variable for what should be withdrew
  62. double actual_amount = my_double;
  63. //-call the withdraw method
  64. dc.withdraw_from(my_double, actual_amount);
  65. //-if the actual amount withdrew is zero,
  66. //-then there was a problem
  67. if (actual_amount == 0)
  68. {
  69. //-show the user there was a problme
  70. cout << "Debit of $" << my_double << " -- Insufficent Funds" << endl;
  71. }
  72. else
  73. {
  74. //-show the user it was successfull.
  75. cout << "Debit of $" << my_double << " Completed" << endl;
  76. }
  77. }
  78. }
  79. //-close the file since we are done
  80. my_file.close();
  81.  
  82. //-print the final balance of the card
  83. //-use the get_balance() method
  84. cout << "The Final Balance Is $" << dc.get_balance() << endl;
  85. }

You probably don't need to see the header file I created, but if you need to, then let me know.
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,580
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 709
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: While loop not ending when reading from file

 
0
  #2
Jan 20th, 2006
>while (! my_file.eof())
That's wrong. The eof member function wasn't designed to be used as a loop condition. Change it to this:
  1. while (my_file.getline(info,sizeof(info)))
Aside from that, there's nothing wrong with your code. It works perfectly on three of my compilers. Trim the code down as much as you can such that the problem still exists. Then give us the trimmed code, a sample file that causes the problem, and details about your OS and compiler.

Haven't I told you that before concerning the exact same problem?
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

Re: While loop not ending when reading from file

 
0
  #3
Jan 20th, 2006
No, this was a different problem. I'm using an older version of bloodshed and it as some really weird lock on files, so once I switched over it worked fine.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,264
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 377
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: While loop not ending when reading from file

 
0
  #4
Jan 21st, 2006
One other thing, if ur using c++ u should try using strings instead of chars - it shud b familiar coming from a java background

And try to avoid !EOF at all costs when reading files, u'll thank me 4 it later.

:rolleyes:
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

Re: While loop not ending when reading from file

 
0
  #5
Jan 21st, 2006
Originally Posted by iamthwee
One other thing, if ur using c++ u should try using strings instead of chars - it shud b familiar coming from a java background
It was actually my first choice to use strings. I would MUCH rather use them over char arrays, but all in all it was good practice, I guess. The reason I used char arrays is because it's the only way I could get it to convert to a double. The strod() wouldn't work with strings.
And try to avoid !EOF at all costs when reading files, u'll thank me 4 it later.
Out of curiosity, why do you say that? You and Narue both warned me, but I have no clue why... I thought it was customary to do this. The example I'm reading from actually shows to use !eof.
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,580
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 709
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: While loop not ending when reading from file

 
0
  #6
Jan 21st, 2006
>The strod() wouldn't work with strings.
Sure it does:
  1. strtod ( s.c_str(), 0 );
I wouldn't recommend using anything but a null pointer for the second argument though. The C-style string produced by c_str() is transient and it's far too easy to invalidate any pointers to it, so you're better off not even trying unless you can quote relevant parts of the standard from memory. A better option would be stringstreams:
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. template <typename T>
  6. T jsw_strtot ( const std::string& s )
  7. {
  8. std::istringstream iss ( s );
  9. T ret;
  10.  
  11. iss>> ret;
  12.  
  13. return ret;
  14. }
  15.  
  16. int main()
  17. {
  18. std::string s = "123.456";
  19. double d = jsw_strtot<double> ( s );
  20.  
  21. std::cout<< d <<'\n';
  22. }
>You and Narue both warned me, but I have no clue why...
The eof flag for a stream is set only after you've tried and failed to read from the stream. So let's say you use this code to read from a file:
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. int main()
  6. {
  7. std::ifstream in ( "test" );
  8. std::string s;
  9.  
  10. while ( !in.eof() ) {
  11. std::getline ( in, s );
  12. std::cout<< s <<'\n';
  13. }
  14. }
And the contents of the file are:
  1. This
  2. is
  3. a
  4. test
Well, the first three strings are read and printed, just like you expect. However, when getline reads "test", you would expect the loop to stop because it's the last string, right? But it doesn't because getline didn't fail with an end-of-file error, it terminated successfully by reading a line. So the loop continues one more time. This is a classic off-by-one error, and it can be especially frustrating when you end up processing the last record in a file twice.

The solution is to use getline's return value as the condition for the loop. That way when getline does fail, it stops the loop at the right time because if getline fails on end-of-file (or an error), execution won't already be in the body of the loop:
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. int main()
  6. {
  7. std::ifstream in ( "test" );
  8. std::string s;
  9.  
  10. while ( std::getline ( in, s ) )
  11. std::cout<< s <<'\n';
  12. }
Now, you can use eof() (or feof()) for a loop condition if you carefully add a kludge to the loop that protects you from the bug, but that's extra work for no real gain.
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,264
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 377
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: While loop not ending when reading from file

 
0
  #7
Jan 21st, 2006
Originally Posted by server_crash
It was actually my first choice to use strings. I would MUCH rather use them over char arrays, but all in all it was good practice, I guess. The reason I used char arrays is because it's the only way I could get it to convert to a double. The strod() wouldn't work with strings.


Out of curiosity, why do you say that? You and Narue both warned me, but I have no clue why... I thought it was customary to do this. The example I'm reading from actually shows to use !eof.
I don't really no why EOF is bad i only been learning c for a few weeks. I'll let sum1 else explain but it is to do with if there is an extra newline and the end of the file it sometimes repeats the data.

And I find it difficult to imagine that the string class cannot convert to double, so much so that u have to use chars? Do sum research and i'm sure u will find sumthing good about converting strings to ints and doubles :lol:
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC