变量继续在循环内重新初始化?

时间:2014-12-02 05:51:54

标签: c++ loops initialization

我是初学者和我自学c ++,有这个练习在跳入C ++,它要求写一个tic tac toe游戏,现在我已经完成了程序的一半但是目前在循环中遇到问题。 我不会把我当前的代码放在这里,因为它的大部分内容都与我的问题无关,但是我写了下面的代码,它类似于我在tic tac toe游戏中遇到的问题:

**无论我给任何-char测试变量赋予什么字符,他们都会因为main()中的while循环而重新初始化为初始字符,这是我知道这个问题的唯一方法是将变量的范围更改为全局,但我不想这样做。

??那么如何阻止变量重新初始化?我无法真正从main()移动while循环,因为它会影响我的tic tac toe游戏中的其他函数...请考虑我是初学者,我只知道循环,条件语句和bools ,我不会理解大编程的话。

谢谢

#include <iostream>

int show(int choice, char x_o);

int main(){
    int i=0;
    int choice;
    char x_o=' ';
    while(i<2){
        //enter 2 and X the first time for example
        //enter 3 and O the second time for example
        std::cin>>choice>>x_o;
        show(choice, x_o);
        ++i;
    }
}

int show(int choice, char x_o){
    char test='1';
    char test2='2';
    char test3='3';

    switch(choice){
        case 1:
            test=x_o;
            break;
        case 2:
            test2=x_o;
            break;
        case 3:
            test3=x_o;
            break;
    }

    std::cout<<test2<<'\n'; //test2 prints 'X' the first time
    //test2 the second time prints '2' again
}

2 个答案:

答案 0 :(得分:1)

很简单。让它们变得静止。

int show(int choice, char x_o){

    static char test='1';
    static char test2='2';
    static char test3='3';
    // ...
}

static关键字表示在方法存在后它们会保留其值。 您可能希望在其他地方设置值:

static char test;
static char test2;
static char test3;

int show(int choice, char x_o){
    // ...
}

答案 1 :(得分:1)

如果定义方法show()的局部变量,则每次声明变量时都会重新定义它们。但是,您可以更改变量的定义方式。你可以举例如:

  • 定义全局
  • 将它们定义为main方法的本地方法,并将它们作为引用或指针传递给show方法

我选择了数字2.这允许您在main方法中本地定义变量。它们的范围将是main()。然后,您可以将引用/指针传递给show方法,该方法允许您在show中读取和更改其值。

相关问题