Sign in to follow this  

reading a file and detecting the 'end of line'

Recommended Posts

OpenGL_Guru    104
hi all. i am reading this file using iostreams and i am having problems detecting the end of line AND end of file.. evidently end of file checks are not good enough. without going into a lot of detail as to what i am doing i hope you can see from the code what may help remedy this:
  for(int i = 0; i < 9; i++)
    input_file.getline(key, MAX_LENGTH, ":");
    char temp[MAX_LENGTH];
    input_file.getline(temp, MAX_LENGTH);
    names[i] temp; //char to a string
the while check doesnt seem to catch the EOL character. how can i make sure that i am not only EOF but also EOL at the same time?? thanks!

Share this post

Link to post
Share on other sites
Zahlman    1682
1) Don't nest the loops like that; you want to loop while you can get a line *and* there is room in the buffer, so there's one loop, and it has that combined condition.

2) Don't use .eof() for looping. It doesn't report true until a read has *already failed*. Instead, use the read operation itself in the loop condition.

3) Don't use the member function .getline() of iostreams. Read directly into std::strings with the free function std::getline() instead. This is considered by many a wart on the standard library design, but it's worth living with (just imagine the alternative of implementing these things yourself!).

for (int i = 0;
i < 9 && getline(input_file, key, ":") && getline(input_file, names[i]);
++i) {} // nothing to do in the loop body.

4) If the limit of 9 strings happens to be arbitrary, then don't settle for arbitrary limits in C++: use std::vector instead -

vector<string> names;
string key, temp;
while (getline(input_file, key, ":") && getline(input_file, temp)) {

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this