2015-08-24 5 views
-3

Я пытаюсь читать символы пробела из определенного файла и хранить их в позиции массива, но когда я запускаю код, я продолжаю получать этот поток: thread 1 exc_bad_access (code = exc_i386_gpflt) , И я не знаю, что я делаю неправильно. Использование Xcode 6.4 бит.Чтение пробелов из текстового файла

#include <iostream> 
#include <string> 
#include<fstream> 
#include <ctype.h> 
using namespace std; 
const int COLS = 8; 
const int ROWS = 8; 
//Function Prototypes 
void displayTop(); 
void displayNumColumn(); 
void displayNumRow(); 
int displayMenu(); 
void displayBoard(); 
char displayHelp(); 
void playGame(char player, int plB, int plW); 
void goToMenu(char x); 
int saveFile(char x, char board[][COLS], char player, int plB, int plW); 
void loadGame(); 
void clearBoard(); 

//Global Variables 
int num = 1; 
char board [COLS][ROWS] = { 

    ' ',' ',' ',' ',' ',' ',' ',' ', 
    ' ',' ',' ',' ',' ',' ',' ',' ', 
    ' ',' ',' ',' ',' ',' ',' ',' ', 
    ' ',' ',' ','W','B',' ',' ',' ', 
    ' ',' ',' ','B','W',' ',' ',' ', 
    ' ',' ',' ',' ',' ',' ',' ',' ', 
    ' ',' ',' ',' ',' ',' ',' ',' ', 
    ' ',' ',' ',' ',' ',' ',' ',' ', 

}; 

int main() { 

    int choice = displayMenu(); 

    switch (choice) { 
     case 1: 
      system("clear"); 
      clearBoard(); 
      displayBoard(); 
      break; 
     case 2: 
      loadGame(); 
      break; 
     case 3: 
      displayHelp(); 
      break; 
     case 4: 
      return 0; 
      break; 
     default: 
      cout << "Please enter a valid choice." << endl; 
      break; 
    } 
    playGame('B', 2, 2); 

} 
//Function to draw and display the board 
void displayBoard(){ 

    displayTop(); 
    num = 1; 
    for (int row = 0; row < ROWS; row++){ 

     displayNumRow(); 
     cout << " |"; 

     for (int column = 0; column < COLS; column++){ 
      cout << board[row][column] << " |"; 
     } 
     cout << endl; 
     displayTop(); 

    } 

    displayNumColumn(); 

} 
// Function to display a horizontal line 
void displayTop(){ 

    cout << " "; 

    for (int i = 0; i < ROWS; i++){ 
     cout << "+----"; 
    } 

    cout << endl; 

} 
//Function to display the alphabets column 
void displayNumColumn(){ 

    cout << " "; 

    for(int i = 1; i <= COLS; i++) { 
     cout << " " << i ; 
    } 
} 
//Function to display the numbers row 
void displayNumRow(){ 

    if (num <= ROWS) { 
     cout << num; 
     num++; 

    } 
} 
// Function to display the menu 
int displayMenu(){ 

    int answer = 0; 
    cout << "Othello\n\n" 
    << "1.New Game\n2.Load Game\n3.Help\n4.Quit\nYour Choice: "; 
    cin >> answer; 
    system("clear"); 
    return answer; 

} 
// Function to display the help window 
char displayHelp(){ 

    char answer = ' '; 

    cout << "How to play Othello\n\nThe object of the game is to have the majority of your colour discs on the board at the end of the game.\n\nInput the cell where you want to place your disc in the form of (rowNumber columnNumber) without the bracket and includng the space.\n\nThe one with the most discs wins!!!!\n\nSo, are you ready to play? (y or n)\n\nYour Choice: "; 
    cin >> answer; 

    if (answer == 'y') 
     displayBoard(); 
    else if (answer == 'n') 
     displayHelp(); 
    else 
     cout << "Invalid input" << endl << endl;; 
    displayHelp(); 

    return answer; 
} 
// Function to act as the game engine 
void playGame(char player, int plB, int plW){ 
    char x = 0; 
    int y = 0; 

    // Infinite for loop to keep switching between players and asking for moves 
    for(;;){ 
     cout << "\n\nScore: W = " << plW << " B = " << plB; 
     cout << "\nPlayer: " << player; 
     cout << "\nPlease make your move : "; 
     cin >> x; 
     cin >> y; 
     cout << endl; 
     goToMenu(x); 
     int xi = x -'0'; 
     // If condition to check for the validity of the input 
     if (xi <= ROWS && y <= COLS && board[xi-1][y-1] == ' ' && cin.good()) { 
      board[xi-1][y-1] = player; 
      displayBoard(); 
     } else { 
      cin.clear(); 
      cin.ignore(100,'\n'); 
      if (saveFile(x, board, player, plB, plW)) { 
       cout << "Game Saved" << endl; 
       if (player == 'B') { 
        plB--; 
       } else { 
        plW--; 
       } 
      } else { 
       cout << "Invalid Input" << endl; 
       if (player == 'B') { 
        plB--; 
       } else { 
        plW--; 
       } 

      } 

     } 

     // If condition to always change the players and add one to their score 
     if (player == 'B') { 
      plB++; 
      player = 'W'; 

     } else { 
      plW++; 
      player = 'B'; 
     } 
    } 

} 

void goToMenu(char x){ 
    if (x == 'm') { 
     main(); 
    } 

} 

int saveFile(char x, char board[][COLS], char player, int plB, int plW){ 
    ofstream savedGame("savedGame.txt"); 

    if (x == 's') { 
     for (int i = 0; i < ROWS; i++) { 
      for (int j = 0; j < COLS; j++) { 
       savedGame << board[i][j]; 

      } 
     } 

     savedGame << player; 
     savedGame << plB; 
     savedGame << plW; 
    }else { 
     return 0; 
    } 
    return 1; 
} 
//Again the same thread: thread 1 exc_bad_access (code=exc_i386_gpflt) 
void loadGame(){ 
    char player; 
    char plB; 
    char plW; 
    int blck; 
    int wht; 
    ifstream savedGame("savedGame.txt"); 
    for (int i = 0; i < ROWS; i++) { 
     for (int j = 0; j < COLS; j++) { 
      savedGame >> noskipws; 
      savedGame >> board[i][j]; 
     } 
    } 
    savedGame >> player; 
    savedGame >> plW; 
    savedGame >> plB; 
    blck = plB - '0'; 
    wht = plW - '0'; 
    displayBoard(); 
    playGame(player, blck, wht); 

} 

void clearBoard(){ 
    for (int i = 0; i <= ROWS; i++) { 
     for (int j = 0; j <= COLS; j++) { 
      board[i][j] = ' '; 
     } 
    } 
    board[3][3] = 'W'; 
    board[3][4] = 'B'; 
    board[4][3] = 'B'; 
    board[4][4] = 'W'; 
} 
+2

Please ** [edit] ** ваш вопрос с [mcve] или [SSCCE (короткий, самосохраненный, правильный пример)] (http://sscce.org) – NathanOliver

+1

'i <= ROWS' <=, который идет вне границ массива. – Galik

ответ

2

Ваша проблема на для петель, все то есть «я < = Rows» поэтому он будет выходить за пределы массива и поэтому он бросает исключение

for (int i = 0; i < ROWS; i++) 

И вы сделали

+1

Ну, вам также нужно изменить на 'for (int j = 0; j john

+0

wow большое спасибо @Juan. Но я до сих пор не понимаю, что вы имеете в виду, «он выйдет за пределы массива». Прошу прощения, если это кажется глупым вопросом, но я вроде новичок в C++. –

+0

Представьте, что вы hace this: int array [5]; Это код, который сообщает, что массив имеет 5 элементов типа int, всего пять. Если вы попытаетесь прочитать шесть int, это не существует, вы будете считывать память, которую вы не используете, потому что может иметь другую переменную, которая не является частью массива (массив - это преемственность блоков памяти). Это то, что вы делали в цикле for, вы вышли за его пределы, и компилятор предупреждает вас об ошибке, потому что это плохо для этого в коде – Juan

Смежные вопросы