c++ -如何正确打印
C++ - How to print this correctly?
我正在用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(" "));
相关文章:
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 打印字符数组地址的正确方法
- C++计算未以正确的格式打印
- std::带有颜色和标题的 clog 包装器无法正确打印整数
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- C++正确书写和打印复数精度 (cout) 的问题?
- 无法在野牛代码中打印正确的值
- 菱形打印不正确
- 排序向量不断修改数据并打印不正确的结果
- C++字符串到字符串打印不正确,无法获取 unicode 路径
- 使用图像 8UC1 c++ 的 unchar 垫正确打印不正确
- 如何打印具有正确有效小数位数的C++双精度
- 最长的公共子序列打印不正确
- 通过 libcups 以编程方式双面打印的正确方法是什么?
- 为什么打印不正确?
- C编程,数组打印不正确
- 在读取文件时打印出正确的值,但在读取文件后打印出垃圾值
- 我的数列没有打印出正确的数字.我能做什么?
- 使用C++中的流打印具有正确缩进的结构化对象
- Win32 编辑打印不正确的字符