Когда ожидается, что программа будет проходить снова, основываясь на пользовательском вводе, это приведет к ошибке сегментации: 11 - PullRequest
0 голосов
/ 05 июня 2018

Я сделал простую программу «камень-ножницы-бумага» на C ++ и попытался реализовать файл main.cpp таким образом, чтобы после игры в игру у пользователя запрашивался ввод, если он захочет поиграть снова.Ответ 'y' должен снова проходить через программу, позволяя пользователю ввести другое имя и переместить выбор, однако программа будет выполнена успешно только один раз, а затем приведет к: RUN FINISHED: ошибка сегментации: 11.

Код:

main.cpp

#include <iostream>
#include <string>
#include "rock-paper-scissorss.h"
using namespace std;

void whoWon(string player_move, string computer_move){
    if(player_move == "rock"){
        if(computer_move == "paper")
            cout<<"You chose rock and the computer chose paper, the computer wins!"<<endl;

        else if(computer_move == "scissors")
            cout<<"You chose rock and the computer chose scissors, you win!"<<endl;

        else
            cout<<"You chose rock and the computer chose rock, it's a tie!"<<endl;
    }

    else if(player_move == "paper"){
        if(computer_move == "scissors")
            cout<<"You chose paper and the computer chose scissors, the computer wins!"<<endl;

        else if(computer_move == "rock")
            cout<<"You chose paper and the computer chose rock, you win!"<<endl;

        else
            cout<< "You chose paper and the computer chose paper, it's a tie!"<<endl;
    }

    else{
        if(computer_move == "rock")
            cout<<"You chose scissors and the computer chose rock, the computer wins!"<<endl;

        else if(computer_move == "paper")
            cout<<"You chose scissors and the computer chose paper, you win!"<<endl;

        else
            cout<<"You chose scissors and the computer chose scissors, it's a tie!"<<endl;
    }
}

int main(int argc, char** argv) {

  char play_again = 'y';

  while(play_again == 'y'){
    cout<<"Please enter your name: "<<endl;
    string name;
    getline(cin,name);
    cout<<"Hello "<<name<<", welcome to Rock-Paper-Scissors!"<<endl;

    Player player_1(name);

    cout<<"Please enter the move you wish to make: "<<endl;
    string move;
    getline(cin,move);
    while(1){
        if((move == "rock") || (move == "paper") || (move == "scissors")){

            player_1.setMoveChoice(move);
            break;
        }

        else{
            cout<<"Invalid move choice! Please enter rock, paper, or scissors"<<endl;
            getline(cin,move);
        }
    } 


    Computer com_1;
    com_1.setMoveChoice();

   string p_move = player_1.getMoveChoice();
   string c_move = com_1.getMoveChoice();


   whoWon(p_move,c_move);



   cout<<"Would you like to play again?(y/n)"<<endl;

   cin>>play_again;
   cout<<"your response was: "<<play_again<<endl;



    } 



 return 0;
}

rock-paper-scissors.cpp:

#include "rock-paper-scissorss.h"
#include <cstdlib>

Computer :: Computer(){
    num_generated = rand() % 3 + 1;
}

void Computer ::  setMoveChoice(){
   if(num_generated == 1)
       move_selected = "rock";

   else if(num_generated == 2)
       move_selected = "paper";

   else
       move_selected = "scissors";

}

string Computer :: getMoveChoice(){
    return move_selected;
}

Computer :: ~Computer(){

    delete this;
}


Player :: Player(string name){
    player_name = name;

}

void Player :: setMoveChoice(string choice){
    move_selected = choice;
}

string Player :: getMoveChoice(){
    return move_selected;
}

Player :: ~Player(){
    delete this;
}

rock-paper-scissorss.h:

#ifndef ROCK_PAPER_SCISSORSS_H
#define ROCK_PAPER_SCISSORSS_H

#include <iostream>
#include <string>
using namespace std;



class Computer{

private:
    int num_generated;
    string move_selected;

public:
    Computer();
    void setMoveChoice();
    string getMoveChoice();
    ~Computer();
};

class Player{

private:
    string move_selected;
    string player_name;

public:
    Player(string);
    void setMoveChoice(string move);
    string getMoveChoice();
    ~Player();
};

#endif /* ROCK_PAPER_SCISSORSS_H */

1 Ответ

0 голосов
/ 05 июня 2018

Вашему классу не нужен деструктор, поскольку он никогда не выделяет явно ресурсы.Удалите:

  Computer :: ~Computer(){
      delete this;
  }

и все подобные функции.

И помните, что даже если вашему классу нужен деструктор, деструктор не должен вызывать:

delete this;

поскольку это будет эффективно выполняться для вас кодом, генерируемым компилятором.Деструктор должен только delete ресурсов, которые вы явно выделяете, в пределах разрушаемого объекта, с new.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...