Я читаю в файле в массив. Это читает каждый символ, проблема возникает, в котором это также читает новую строку в текстовом файле.
Это - плата судоку, вот мой код для чтения в символе:
bool loadBoard(Square board[BOARD_SIZE][BOARD_SIZE])
{
ifstream ins;
if(openFile(ins)){
char c;
while(!ins.eof()){
for (int index1 = 0; index1 < BOARD_SIZE; index1++)
for (int index2 = 0; index2 < BOARD_SIZE; index2++){
c=ins.get();
if(isdigit(c)){
board[index1][index2].number=(int)(c-'0');
board[index1][index2].permanent=true;
}
}
}
return true;
}
return false;
}
как я сказал, это читает файл, отображается на экране, просто не в правильном порядке, когда это встречается с \n
Ну в вашем формате файла вы можете просто не сохранять новые строки, или вы можете добавить ins.get() в цикл for.
Вы также можете обернуть c=ins.get() в функцию типа getNextChar(), которая будет пропускать все новые строки.
Думаю, вам нужно что-то вроде этого:
for (int index1 = 0; index1 < BOARD_SIZE; index1++)
{
for (int index2 = 0; index2 < BOARD_SIZE; index2++){
//I will leave the implementation of getNextDigit() to you
//You would return 0 from that function if you have an end of file
//You would skip over any whitespace and non digit char.
c=getNextDigit();
if(c == 0)
return false;
board[index1][index2].number=(int)(c-'0');
board[index1][index2].permanent=true;
}
}
return true;
У вас есть несколько хороших вариантов. Либо не сохраняйте символы новой строки в файле, либо явно отбрасывайте их в своем цикле, либо используйте std :: getline ()
в
.
Например, используя getline ()
:
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
using namespace std;
// ...
string line;
for (int index1 = 0; index1 < BOARD_SIZE; index1++) {
getline(is, line); // where is is your input stream, e.g. a file
if( line.length() != BOARD_SIZE )
throw BabyTearsForMommy();
typedef string::iterator striter;
striter badpos = find_if(line.begin(), line.end(),
not1(ptr_fun<int,int>(isdigit)));
if( badpos == line.end() )
copy(board[index1], board[index1]+BOARD_SIZE, line.begin());
}
Вы можете поместить ins.get() в цикл do while:
do {
c=ins.get();
} while(c=='\n');