ifstream object.eof()不起作用

use*_*120 1 c++

我想我可能需要在我的while条件下使用布尔值bValue = false:

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

}
Run Code Online (Sandbox Code Playgroud)

为什么我不能输入文本文件的完整路径名?

这可能是因为eof.他们的语法是否可以模拟eof的布尔语句?

我能有......吗:

while ( !object == true )
{
// parase contents of file
}
Run Code Online (Sandbox Code Playgroud)

小智 7

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
   }
}
Run Code Online (Sandbox Code Playgroud)