c++ - 程序不会编译

标签 c++ compiler-errors fstream ifstream ofstream

这是代码

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

该程序应该读取生成的拼图。确保其有效并将其写入另一个文件。通常我擅长找出错误,但这个是一团糟。它吐出一些关于包含 iostream 的内容,并引用了与我无关的文件。我猜它是将 fstreams 传递给函数或其他东西时出现的一些错误。有什么线索吗?

最佳答案

您应该传递对流对象的引用:

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
}

此更改是必需的,因为 ifstreamofstream 都有一个 =delete 复制构造函数。 (帽子提示:@awesomeyi)

关于c++ - 程序不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20365253/

相关文章:

c++ - fstream 和 wfstream 的基类

c++ - 创建 vector 集

c - 无法识别的调试选项 : 1 [enabled by default]

c++ - Waf - 未找到源 : None

gcc - 内部编译器错误 : Bus error with LLVM GCC 4. 2 编译器

c++ - 如何将带有 vector 或其他标准库容器的对象保存到 C++ 中的二进制文件?

c++ - OpenGL 翻译错误,C1068 和 C2003

c++ - TypeCasting 在 C++ 中将 <int, class A> 映射到 <int, class B>

c++ - Winsock:监听和接收(差异)

c++ - 将字节写入 .Bin 文件