我正在尝试用c ++初始化一个tic-tac-toe板,但输出总是给我六进制值。有没有办法将它们转换为实际的字符串值?
#include <iostream>
#include<string>
using namespace std;
int main()
{
string tab[5][5] = { "1","|","2","|","3",
"-","+","-","+","-",
"4","|","5","|","6",
"-","+","-","+","-",
"7","|","8","|","9" };
for(int i = 0; i <= 24; i++)
{
cout << tab[i] << endl;
}
}
答案 0 :(得分:4)
您将$.ajaxSetup({
beforeSend: function (request, details) {
request.success(function (response) {
analysis.sendData(details, response);
})
}
})
的值发送给tab[i]
,因此您将获得内存地址。
您可能希望更深层次地嵌套项目,例如cout
。
答案 1 :(得分:4)
tab[i]
是std::string[]
- 即std::string
而不是std::string
本身的数组。
使用ranged - for
代替您的输出。除标准库容器外,它还可以使用内置数组:
for (const auto &row : tab) {
for (const auto &c : row) {
cout << c;
}
cout << endl;
}
答案 2 :(得分:2)
当然,在输出位置提出循环的答案是正确的。如果您碰巧要在应用程序的许多不同位置输出您的tic tac toe字段,您可能更愿意将其封装起来。一个可能的解决方案是有一个tic tac toe类:
struct TicTacToe : public std::array<std::array<int, 3>, 3> {
TicTacToe() :
// not sure, if the initialization will work like that
std::array<std::array<int, 3>, 3>{{0,0,0},{0,0,0},{0,0,0}}
{};
};
然后为它定义一个输出运算符:
auto operator << (std::ostream& out, const TicTacToe& field)
-> std::ostream& {
return
out << std::accumulate(std::begin(field),
std::end(field),
std::string{},
[](const std::string& a,
const std::array<int, 3> b)
-> std::string {
return
std::accumulate(std::begin(b),
std::end(b),
std::string{},
[](const std::string& a, int b)
-> std::string {
return std::string{b < 0 ?
"O" :
(b > 0 ? "X" : " ")} +
(a.empty() ? "" : "|")
}) +
(a.empty() ? "" : "\n-+-+-\n");
});
}
请注意,我还没有测试过此代码。它旨在为您提供一个想法,而不是复制粘贴的来源。
答案 3 :(得分:0)
这更像是非常感谢!
#include <iostream>
#include<string>
using namespace std;
int main()
{
string tab[5][5] = { "1","|","2","|","3",
"-","+","-","+","-",
"4","|","5","|","6",
"-","+","-","+","-",
"7","|","8","|","9" };
for(int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
cout << tab[i][j];
if (j == 4)
cout << endl;
}
}
}