繁体   English   中英

C ++ User输入一个char,变量保持为0

[英]C++ User inputs a char, the variable stays 0

我正在尝试创建一个井字游戏,其中用户输入一个数字(对应于他想要放置他的X或O的位置),但接收数字的变量(Move)保持为0,无论是什么输入是。 你能帮我弄清楚要解决的问题,这样变量实际上会收到用户输入的内容吗? 以下是接收移动的函数的代码:

int FDeclarations::GetMove(){
int Move;
std::cin >> Move;
return Move;}

这是通过switch语句的函数的代码(由于变量“Move”始终为0,所以没有任何工作)

int FDeclarations::PlaceMove(){
switch (Move)
{
case(1):
    if (turn == false) { TopLeft = 'x'; }
    else { TopLeft = 'o'; }
    break;
case(2):
    if (turn = false) { TopMid = 'x'; }
    else { TopMid = 'o'; }
    break;
case(3):
    if (turn = false) { TopRight = 'x'; }
    else { TopRight = 'o'; }
    break;
case(4):
    if (turn = false) { MidLeft = 'x'; }
    else { MidLeft = 'o'; }
    break;
case(5):
    if (turn = false) { MidMid = 'x'; }
    else { MidMid = 'o'; }
    break;
case(6):
    if (turn = false) { MidRight = 'x'; }
    else { MidRight = 'o'; }
    break;
case(7):
    if (turn = false) { BotLeft = 'x'; }
    else { BotLeft = 'o'; }
    break;
case(8):
    if (turn = false) { BotMid = 'x'; }
    else { BotMid = 'o'; }
    break;
case(9):
    if (turn = false) { BotRight = 'x'; }
    else { BotRight = 'o'; }
    break;
}


table();
    return 0;
}

这是我的变量声明:

        class FDeclarations
{
    public:
        int PlaceMove();
        int GetMove();
        int CheckWin();
        void table();

    private:
        bool turn = false;
        int Move;
        char TopLeft = '1';
        char TopMid = '2';
        char TopRight = '3';
        char MidLeft = '4';
        char MidMid = '5';
        char MidRight = '6';
        char BotLeft = '7';
        char BotMid = '8';
        char BotRight ='9';
        bool XWin;
        bool OWin;
    };

在你的功能

int FDeclarations::GetMove() {
    int Move;
    std::cin >> Move;
    return Move;
}

您声明一个名为Move变量,该变量是该函数的本地变量。 这与类中声明的成员变量Move不同。 C ++更喜欢绑定到函数级变量。

除非你使用GetMove的返回值来设置成员变量Move in code not you not us us,那么成员变量Move将永远不会改变,从而导致你的问题。

FDeclarations::GetMove()您需要设置类的私有成员Move到用户将输入的任何内容,而不是FDeclarations::GetMove()成员的局部变量。 所以快速修复将是:

int FDeclarations::GetMove(){
    std::cin >> Move;
    return Move;}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM