需要从输入文件中跳过换行符char(\n)

cod*_*ail 5 c++ newline sudoku

我在一个文件中读到一个数组.它正在读取每个char,问题出现在它还在文本文件中读取换行符.

这是一个数独板,这是我在char中读取的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

就像我说的那样,当它遇到\n时,它会读取文件,显示在屏幕上,但是顺序不正确

Bri*_*ndy 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;
Run Code Online (Sandbox Code Playgroud)