c++ - 变量不断在循环内重新初始化?

标签 c++ loops initialization

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

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

??那么我怎样才能阻止变量被重新初始化呢?我真的不能从 main() 中移动 while 循环,因为它会影响我的井字游戏中的其他功能...请考虑我是初学者,我只知道循环、条件语句和 bool 值,我会不懂编程大词。

谢谢

#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
}

最佳答案

很简单。使它们静态。

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){
    // ...
}

关于c++ - 变量不断在循环内重新初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27242753/

相关文章:

c++ - 0xDEADBEEF 相当于 64 位开发?

c++ - 创建 Qml/C++ 应用程序作为插件

c++ - 我如何发送 gzip 而不是通过跳过 header 缩小

C++ CRTP(模板模式)问题

swift - 从 Swift 3 中的 URL 列表下载内容的安全方法

c++ - 使用空标记结构,编译器声称我缺少初始化器,但我不是

R - 如何使用循环根据匹配名称列表复制和更改数据框

c - c 中的滚动总计循环

c++ - 两个程序具有相同的代码: floating point overflow

python - 如何对python中复杂类中的方法进行单元测试?