为什么写入文件的函数会一直重复,然后才会出现问题?

时间:2018-03-29 17:12:39

标签: c++

我目前正在用c ++创建一个数独游戏。我完成了大部分程序,除了一个给我带来麻烦的功能。以下是以下功能:

void writeGame(char board[][9])
{
   ofstream fout;
   char fileDestination[256];

   cout << "What file would you like to write your board to: ";
   cin >> fileDestination;

   fout.open(fileDestination);
   if (fout.fail())
   {
      cout << "Output unsuccessful.\n";
   }
   else
   {
      cout << "Board written successfully\n";
   }

   for (int row = 0; row < 9; row++)
   {
      for (int col = 0; col < 9; col++)
      {
         fout << board[col][row];
      }
   }
   fout.close();
}

我在另一个函数中也有一个switch语句,具有此函数的特定大小写:

void prompt(char board[][9])
{
   char option;
   cout << "> ";
   cin >> option;

   switch (option)
   {
      case 'Q':
         writeGame(board);
         break;
      default:
         cout << "Error";
         break;
   }
}

当程序提示用户输入大小写时,writeGame函数应运行并输出:

> Q
What file would you like to write your board to: "file.txt"
Board written successfully

然而,在输出成功写入电路板后,它会重复该功能并输出:

> Q
What file would you like to write your board to: "file.txt"
Board written successfully
What file would you like to write your board to:
//exp: no output
//then the program times out

我在另一个显示电路板的功能中调用提示功能:

void displayBoard(char board[][9])
{
   char option;
   cout << "   A B C D E F G H I\n";

   for (int row = 0; row < 9; row++)
   {
      cout << row + 1 << "  ";
      for (int col = 0; col < 9; col++)
      {
         if (board[col][row] == '0')
         {
            cout << " ";
         }
         else
         {
            cout << board[col][row];
         }
         if (col == 2 || col == 5)
         {
            cout << "|";
         }
         else if (col != 8)
         {
            cout << " ";
         }
      }

      if (row == 2 || row == 5)
      {
         cout << "\n   -----+-----+-----\n";
      }
      else
      {
         cout << endl;
      }
   }
   cout << endl;
   prompt(board);
}

我尝试在我的writeGame函数中使用for循环中的break但是没有效果,我认为switch语句中的break会停止该函数。我似乎无法弄清楚如何防止函数重复然后超时。感谢任何提示,谢谢。

0 个答案:

没有答案