Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

detecting end of file?

Status
Not open for further replies.

dnnymak

MIS
Sep 19, 2004
9
US
How do I detect end of file when reading from a file. I have tried cin.eof(), but I think this is only for reading from keyboard input.

Also, does c++ automatically detect white space when reading files or is it ignored?

Thank you all,
dnnymak
 
.eof can be used when reading in a file, like:

while (!file.eof())
{
}

its been a while since I've used C++, but you may be able to do:

while (file != EOF)
{
}

As for reading spaces, it depends on the type of input you are using...some file reading does ignore whitespace others do not...it also depends on if you are going to be reading in the entire line at a time...like cin.get(somevariable, Linelength) or cin.getline(somevariable) .... etc.

Good luck,
kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
no problem...glad to help out.

Kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
Be careful about checking for eof(), since that function returns true only after an attempt is made to read past the end of the file. Are you using operator>> or getline? Here is an example of reading a file one word at a time (skipping all whitespace) that ends when the end of file is reached:
Code:
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream inFile("test.txt");
    if (!inFile)
        return EXIT_FAILURE;

    std::string word;
    while (inFile >> word)
    {
        std::cout << word << std::endl;
    }
}
 
thanks uolj,

thats what I was looking for. I am using the following to read the file:

for (int i = 0; i <= M -1; i++)
{
for (int j = 0; j <= N -1; j++)
{
InputFile1 >> imatrix[j];
}
}

and I wanted to test for a premature eof.

thanks again,
dnnymak
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top