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

那么在您的文件格式中,您可以简单地不保存换行符,或者您可以添加一个 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;
于 2010-04-01T00:41:39.383 回答
0

你有几个不错的选择。要么不将换行符保存在文件中,要么在循环中明确丢弃它们,要么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 回答