Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c++ - ifstream object.eof() not working

I think i might need to use a boolean bValue = false for my while condition:

char cArray[ 100 ] = "";
ifstream object;
cout << "Enter full path name: ";
cin.getline( cArray, 100 );
if ( !object ) return -1   // Path is not valid? This statement executes why?

ifstream object.open( cArray, 100 );

// read the contents of a text file until we hit eof.
while ( !object.eof() )
{
// parse the file here

}

Why can i not enter the full path name of the text file?

It might be because of the eof. Is their syntax for a boolean statement that can emulate eof?

Can i have:

while ( !object == true )
{
// parase contents of file
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please will you and everyone else note that the correct way to read a text file does NOT require the use of the eof(), good(), bad() or indifferent() functions (OK, I made the last one up). The same is true in C (with fgets(), feof() et al). Basically, these flags will only be set AFTER you have attempted to read something, with a function like getline(). It is much simpler and more likely to be correct to test that read functions, like getline() have actually read something directly.

Not tested - I'm upgrading my compiler:

#include <iostream>
#include <fstream>
#include <string>
using namespacr std;

imt main() {

   string filename;
   getline( cin, filename );

   ifstream ifs( filename.c_str() );
   if ( ! ifs.is_open() ) {
       // error
   }

   string line;
   while( getline( ifs, line ) ) {
       // do something with line
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...