Domanda

Here is the code

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

class sudoku {
    public:
        void read(ifstream ifs);
        void write(ofstream ofs);

    private:
        int puzzle[9][9];

};

void sudoku::read(ifstream ifs){
    int row;
    int col;
    int value;
    int linenum = 1;
    bool error = false;

    while(ifs >> row){
        ifs >> col;
        ifs >> value;

        if(row < 0 || row > 8){
            cerr << "Incorrect Row Value: " << row << " Line Number: " << linenum;
            error = true;
        }

        if(col < 0 || col > 8){
            error = true;
            cerr << "Incorrect Col Value: " << col << " Line Number: " << linenum;
        }

        if(value < 1 || value > 9){
            error = true;
            cerr << "Invalid Value: " << value << " Line Number: " << linenum;
        }

        if (! error)
            puzzle[row][col] = value;

        error = false;
    }
}

void sudoku::write(ofstream ofs){

    for (int i = 0; i < 9; i++){
        for (int j = 0; j < 0; j++){

            if(puzzle[i][j] != 0){
                ofs << i << ' ' << j << ' ' << puzzle[i][j] << endl;
            }

        }

    }

}


int main(int argc, char* argv[]){

    sudoku sudopuzzle;

    string filename = argv[1];

    int found = filename.find(".txt");
    if(found == filename.npos) {
        cout << "No .txt extension" << endl;
        return 0;
    }


    ifstream ifs;
    ifs.open(filename.c_str());

    sudopuzzle.read(ifs);

    ifs.close();

    filename.resize(filename.size()-4);

    filename.append("_checked.txt");

    ofstream ofs;
    ofs.open(filename.c_str());

    sudopuzzle.write(ofs);
    ofs.close();

    return 0;
}

This program is supposed to read a generated puzzle. make sure its valid and write it to another file. Normally I am good at figuring out errors but this one is a mess. It spits out stuff referring to the inclusion of iostream and cites files that I have nothing to do with. Im guessing its some error that comes with passing fstreams to funcitons or something. any clue?

È stato utile?

Soluzione

You should be passing a reference to the stream objects:

class sudoku {
    public:
        void read(ifstream &ifs);
        void write(ofstream &ofs);

    private:
        int puzzle[9][9];

};

void sudoku::read(ifstream &ifs){
    // sudoku::read code here
}

void sudoku::write(ofstream &ofs){
    // sudoku::write code here
}

This change is required because both ifstream and ofstream have a =delete copy constructor. (Hat tip: @awesomeyi)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top