c++ - 通过在 C++ 中使用连接调用它来编辑字符串

标签 c++

我是一个非常新的 C++ 用户(也是 StackOverflow 的新用户),我正在尝试编写一个非常基本的 Tic-Tac-Toe(Naughts and Crosses)游戏。我不确定如何在更新时呈现板。

我的主要问题是是否可以使用串联来调用字符串。我有一个数组设置,使用 0 表示空,1 表示 X,2 表示 O 来索引板的 9 个空间的状态。如果我在用户定义的 renderBoard() 中设置 9 个变量函数名为 bit1、bit2 等;我可以这样称呼他们吗:

void renderBoard()
{
    int i = 1;
    string bit1;
    string bit2;
    string bit3;
    string bit4;
    string bit5;
    string bit6;
    string bit7;
    string bit8;
    string bit9;

    while (i < 10)
    {
        if (Spaces[i] = 0)
        {
            (bit + i) = * //This is the main bit I'm wondering about
        }
        else
        {
            //Check for 1, 2, and edit the string bits accordingly
        }
        ++i;
    }
    //Put all of the strings together, as well as some more strings for adding the grid
    //Output the whole concatenated string to the command line
}

如果有人知道更好的方法,请告诉我。我尝试通过谷歌搜索和浏览各种 C++ 帮助网站,但我发现除了冗长而具体的解释外,很难通过任何其他方式表达我的特殊情况。

谢谢你的帮助!!

最佳答案

如果我正确理解你的问题,你的问题是你想使用变量i访问名为bit1bit2等的字符串> 像 bit + i

不,你不能那样做! 它将抛出一个编译时错误。

如果我没有得到你要找的东西,请纠正我。

但我仍然有一个问题,为什么要使用字符串变量 bit1bit2 等? 我认为您只想在这些字符串中存储单个数字值。如果是这种情况,您可以只使用长度为 9 的单个字符串。

您可以按如下方式执行此操作:

int i = 0; //because string indices start from 0 and also array indices.
string bit(9, ' '); //declare a string of length 9 with default value of a space (you can modify it with your default value)
while (i < 9) { // i < 9 because highest index will be 8 
     if (Spaces[i] == 0) { 
         bit[i] = '*';
     } else { 

     } 
    ++i;
 }

关于c++ - 通过在 C++ 中使用连接调用它来编辑字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57351952/

相关文章:

c++ - 如何高效复制istringstream?

c++ - C++ 中的默认引用参数

c++ - std::namespace 中是否有 C++ 版本的 C 标准库函数?

c++ - 为什么我的 while 参数没有被确认

c++ - cstring 数组有问题

c++ - 为什么这个程序不会运行,但它会构建?

c++ - C++ 宏展开的一个问题

c++ - 字符大小和 const void*

c++ - 为什么继承的构造函数不应该继承默认参数?

C++/C int32_t 和 printf 格式 : %d or %ld?