我正在嘗試多載 >> 運算子,以便我可以打開一個打開的 ifstream 檔案并將其內容讀入我的類中的陣列中。出于某種原因,當我做這樣的事情時
ifstream puzzle;
Sudoku x; //Sudoku is the name of myclass
puzzle.open("example.txt", ios::in);
puzzle >> x;
它不會將我想要的內容轉移到我的 x 物件。運行我的代碼后沒有錯誤彈出,但是當我查看物件的陣列中的內容時,它只有一個充滿零的陣列,因為它已被初始化。這是我的代碼的基本重新創建。
class Sudoku
{
public:
Sudoku();
~Sudoku(){}
int getValue(int row, int col){return grid[row][col];}
void setValue(int row,int col,int num) {grid[row][col]=num;}
friend ifstream& operator>>(ifstream &input, Sudoku &s);
private:
int grid[9][9];
};
ifstream& operator>>(ifstream &input, Sudoku &s)
{
int x = 0, i = 0, j = 0;
while (input >> x)
{
if (j >= 9)
{
i ;
j = 0;
}
if (i >= 9)
{
return input;
}
s.setValue(i, j, x);
j ;
}
return input;
}
uj5u.com熱心網友回復:
x如果輸入檔案的格式正確?,您的函式就可以正常填充- 但有一個很大的缺陷。你看,while (input >> x),檢查,如果你之前應該閱讀。如果此時您已經讀取了檔案中的所有值,它將failbit在輸入流上設定,因此如果您執行此操作以檢查:
if(puzzle >> x) {
std::cout << "success\n";
} else {
std::cout << "failure\n";
}
它會列印“失敗”,即使讀取了所有值 - 只是因為您試圖過多地讀取一個值。
我建議將其簡化為僅讀取與 (9 x 9) 一樣多的值,并且使其從any 讀取istream,而不僅僅是從ifstreams讀取。
該friend宣告變為:
friend std::istream& operator>>(std::istream &input, Sudoku &s);
和實施:
std::istream& operator>>(std::istream &input, Sudoku &s) {
for(int i = 0; i < 9; i) {
for(int j = 0; j < 9; j) {
// There's no need to use setValue since you made it a friend
input >> s.grid[i][j];
}
}
return input;
}
?檢查您的輸入檔案。數字之間有空格嗎?如果沒有 - 確保它有,否則你operator>>將無法作業。
uj5u.com熱心網友回復:
下面是一個完整的作業示例。你會注意到一些事情。
- 我從不使用朋友類,也沒有理由這樣做。
- 我做了一個 operator>> 函式,這樣我就可以把它寫回來。
- 我的 operator<< 需要一個 istream 而不是更具體的 ifstream。該方法不應該關心它是一個 ifstream,所以讓它更通用更好。
- 而且我的比你的簡單。
它編譯(至少在 C 17 下)并正常運行。我不完全確定為什么你的不起作用。
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::ifstream;
using std::istream;
class Sudoku
{
public:
Sudoku() {};
~Sudoku(){}
int getValue(int row, int col){return grid[row][col];}
void setValue(int row,int col,int num) {grid[row][col]=num;}
private:
int grid[9][9];
};
std::istream & operator>> (std::istream &input, Sudoku &s)
{
int row = 0;
int col = 0;
while (row < 9) {
int cellValue;
if (!(input >> cellValue)) {
std::cout << "Out of input." << endl;
return input;
}
s.setValue(row, col, cellValue);
if ( col >= 9) {
row;
col = 0;
}
}
return input;
}
std::ostream & operator<< (std::ostream &oStr, Sudoku &s) {
for (int row = 0; row < 9; row) {
for (int col = 0; col < 9; col) {
if (col % 3 == 0) {
oStr << " ";
}
oStr << s.getValue(row, col);
}
oStr << endl;
}
return oStr;
}
int main(int, char **) {
std::ifstream input("sudoku.txt");
Sudoku sudoku;
input >> sudoku;
std::cout << sudoku << std::endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325431.html
標籤:C
上一篇:康威的生命游戲演算法不起作用
