Tuesday, May 17, 2011

C++ Loop construction for file input.

The following loop setup will yield the best results for file input and avoids many common mistakes that have to do with the eof() member returning true only after the eof() has been reached.




int main()
{
using namespace std;
ifstream inFile("somefile.txt");
//check for errors, etc.

string input;
while( inFile >> input ) //< -- loop
{
//Processing.
}

inFile.close();
}

19 comments:

  1. Yes, often the loop condition is:
    while( ! inFile.eof() )

    which means the last character is read twice due to the condition described above.

    ReplyDelete
  2. Smart. Will think about it next time I use it haha

    ReplyDelete
  3. Going to have to remember this one, I guess.

    ReplyDelete
  4. Can you use this for rsbot?

    ReplyDelete
  5. If it's open-source then you can make any number of modifications.

    ReplyDelete
  6. Oh yeah this really avoids a lot of mistakes.

    ReplyDelete
  7. wait im kinda shit at computer code whats this do

    ReplyDelete
  8. ...syntax... no just no :D almost ruind my graduation

    ReplyDelete
  9. haha it's just a simple tip for beginners. Maybe if I posted a class that did something useful it would better target my audience?

    ReplyDelete
  10. yea looks legit, but then again i've only take like one or two computer classes

    ReplyDelete
  11. Tomorrow I will have a post on STL algorithms/containers.

    STL = a pure computation library for C++ (amazing)

    ReplyDelete
  12. lol you posting your C++ notes on here? good review i suppose

    ReplyDelete
  13. Notes? No, I use programming forums a lot and these kinds of mistakes are very common.

    Even actual programmers sometimes don't know better, but in my experience they typically are accustomed to using C rather than C++.

    ReplyDelete
  14. Nice post, keep up the good work!

    ReplyDelete