Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...