c++ -如何正确打印

C++ - How to print this correctly?

本文关键字:打印 何正确 c++      更新时间:2023-10-16

我正在用c++编程一个小游戏(Tic Tac Toe),并且在打印板时遇到问题。

代码如下("syntax.h"是一个头文件,包含print、println、input等函数):

#include "syntax.h" // contains helpful functions such as "print" and "println" to shorten code
char board[3][3];
void print_board();
int main()
{
    print_board();
}
void print_board()
{
    for (int i = 0; i < 3; i++)
    {
        println("-------");
        for (int j = 0; j < 3; j++)
        {
            print("|" + board[i][j] + " "); // ERROR - Cannot add two pointers
        }
        println("|");
    }
    println("-------");
    input();
}

print是"syntax.h"中的一个函数,它接收一个字符串变量并使用cout打印它,然后刷新输出缓冲区。

现在,我不能像上面那样打印字符串,因为它告诉我不能将两个指针相加。

我明白为什么会发生这种情况,那是因为打印参数中的"实际上是char*而不是string变量,我不能将它们加在一起。

问题是我也不想做另一个打印函数调用,并在同一个函数调用中打印所有这3个字符串。

那么我应该如何在没有错误的情况下打印上面的内容呢?

代替

print("|" + board[i][j] + " ");

print((std::string("|") + board[i][j] + " ").c_str())

std::string具有用于连接的重载操作符+。别忘了

#include <string>

使用sprintf()函数:

//print("|" + board[i][j] + " "); // ERROR - Cannot add two pointers 
char buffer[100];   
sprintf(buffer, "| %s ", board[i][j]);
print(buffer); 

而如果你想使用字符串类型可以这样做:

//print("|" + board[i][j] + " "); // ERROR - Cannot add two pointers    
print(string("|") + string(board[i][j]) + string(" "));