0

I've a constructor for the Engine class which reads in the contents of king-moves.movelist into a std::map using an input file stream. The function below illustrates the same:

Engine::Engine() {
    std::ifstream dbFile;
    dbFile.open( "../data/king-moves.movelist" );

    if( !dbFile )
        std::cout << "Error: Unable to read king moves" << std::endl;
    else {
        unsigned long long a, b;
        while( true ) {
            dbFile >> a >> b;
            m_k_moves_db.insert( std::pair< unsigned long long, unsigned long long >( a, b ) );
            if( dbFile.eof() ) 
                break;
        }
    }
    std::cout << m_k_moves_db.size() << std::endl;
}

The Engine class can be minimally represented as follows:

class Engine {
private:
    std::map< unsigned long long, unsigned long long > m_k_moves_db;

public:
    // Constructors and other functions
};

Now when I try to print the contents of m_k_moves_db, I'm met with the error message Error: Unable to read king moves.

Is there anything that I'm doing wrong while reading in from the file stream?

  • 2
    the error is reported before you even started to read from the file. Usually the cause for a file not opening correctly is that it isnt in the location you expect it to be (relative to the working directory) – 463035818_is_not_an_ai Sep 28 '21 at 13:12
  • 1
    Are you familiar with the development environment you're using? A lot of the time, this sort of problem is caused by the working directory not being what you expect. A quick trick that might help is, at the beginning of `main()`, to print the value of `argv[0]` – Tim Randall Sep 28 '21 at 13:15
  • 2
    Note that you're checking `eof()` too late. See [this question](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) for how to write an input loop. – molbdnilo Sep 28 '21 at 13:16
  • A more idiomatic loop would be `while (dbFile >> a >> b) { m_k_moves_db[a] = b; }`. There is no point to using `insert` if you ignore its return value. – molbdnilo Sep 28 '21 at 13:31
  • This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default-initializing them and immediately overwriting the default values. In this case, that means changing `std::ifstream dbFile; dbFile.open( "../data/king-moves.movelist" );` to `std::ifstream dbFile( "../data/king-moves.movelist" );`. – Pete Becker Sep 28 '21 at 13:36
  • @463035818_is_not_a_number I just wrote another program using the exact same code to test the correctness of my implementation. And everything worked as intended. The problem seems to be something else altogether I guess! – Priyanshu Sep 28 '21 at 14:14

0 Answers0