意外接受用户输入c ++类

时间:2016-06-16 14:07:19

标签: c++ eclipse oop

刚开始使用C ++中的类,我在请求用户输入时遇到奇怪的事情。

条件语在getUserWantToPlay()成员函数中接受两个结果:' y'或者' n'。否则,它将输出请求正确响应的消息。我正处于构建的早期阶段,我只是对这个成员函数进行了一些测试,我注意到当我输入" yes"或"不"就好像我输入了' y'或者' n'。为什么会这样?

申请代码

//implementation of TicTacToe
//Using classes this time

#include <iostream>
#include "TicTacToeClass.h"


int main()
{

    //Assumes no play unless user decides they want to play and initializes game variable to TicTacToe class
    bool play = false;
    TicTacToe game;

    play = game.getUserWantToPlay();

    while(play == true)
    {


        std::cout << "Playing the game" << std::endl;
        break;

    }

    return(0);
}

班级实施

//TicTacToe class implementation
//Leeroy Jenkins

#include "TicTacToeClass.h"
#include <iostream>


bool TicTacToe::getUserWantToPlay()
{

    char response;
    bool invalidResponse = true;
    bool play = false;

    while(invalidResponse == true)
    {

        std::cout << "Would you like to play a new game of TicTacToe? (y/n) " << std::endl;
        std::cin >> response;

        if(response == 'y')
        {
            invalidResponse = false;

            play = true;
        }
        else if(response == 'n')
        {
            std::cout << "No Problem!";
            invalidResponse = false;
        }
        else
        {
            std::cout << "Please input a proper response (y/n)" << std::endl;
        }

    }

    return play;
}

0 个答案:

没有答案