这是代码
#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和引用我无关的文件。我猜测将fstream传递给funcitons或其他东西时会出现一些错误。任何线索?
答案 0 :(得分:1)
您应该传递对流对象的引用:
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
}
此更改是必需的,因为ifstream
和ofstream
都有=delete
副本构造函数。 (帽子提示:@awesomeyi)