ifstream object.eof() not working

前端 未结 2 1337
青春惊慌失措
青春惊慌失措 2020-12-12 03:57

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         


        
相关标签:
2条回答
  • 2020-12-12 04:16

    The ifstream::open function takes a filename and an optional mode. Since you want to read the whole file, why not just start at the begining:

    ifstream obj(cArray);
    if (obj) { // file successfully opened for reading
        while (obj.good()) {
            // read in a line at a time
            string line;
            getline(line, obj);
            if (!line.empty()) { // we have something to work with
               // parse
            }
        }
    }
    

    Of course, a sleeker version is to test for getline in the while loop as Neil Butterworth.

    0 讨论(0)
  • 2020-12-12 04:42

    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
       }
    }
    
    0 讨论(0)
提交回复
热议问题