6

ファイルを配列に読み込んでいます。各文字を読み取っていますが、テキストファイルの改行も読み取るという問題が発生します。

これは数独ボードです。文字を読み取るためのコードは次のとおりです。

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 に遭遇したときに正しい順序ではありません

4

3 に答える 3

2

ins.get() を do while ループに入れることができます。

do { 
    c=ins.get();
} while(c=='\n');
于 2010-04-01T00:50:34.610 に答える
1

あなたのファイル形式では、単に改行を保存することはできません。または、 for ループに ins.get() を追加することもできます。

改行をスキップする getNextChar() のような関数で c=ins.get() をラップすることもできます。

私はあなたがこのようなものが欲しいと思います:

 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;
于 2010-04-01T00:41:39.383 に答える
0

いくつかの良いオプションがあります。改行をファイルに保存しないか、ループで明示的に破棄するか、 in を使用std::getline()<string>ます。

たとえば、次を使用し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());
}
于 2010-04-01T00:57:46.267 に答える