了解 c++ 中的 cout 格式化

Understanding cout formating in c++

我用 C++ 编写代码已经有一段时间了。当我在做一个项目时,我遇到了一个可能对我有帮助的解决方案,但我不明白它是如何工作的。也许有人可以帮助我了解正在发生的事情。

for (int i = 1; i < length_of_board - 1; i++) {
  cout << i;
  for (int j = 1; j < length_of_board - 1; j++) {
    cout << (((i > 9) && (j < 2)) ? " " : "  ")
         << ((boardArray[i][j] == '8') ? '.' : boardArray[i][j]);
  }

  cout << endl;
}

我怎么知道 cout 在做什么,我可以用两个 if 语句替换它吗?

三元运算符的工作方式类似于

query ? if_true : if_false;

在你的例子中,这个表达式被展开为

if((i>9)&&(j<2)) cout<<" "; else cout<<"  ";
if(boardArray[i][j]=='8') cout<<'.'; else cout<<boardArray[i][j];

或者为了方便阅读;

if((i>9)&&(j<2))
{
    cout<<" ";
}
else
{
    cout<<"  ";
}
if(boardArray[i][j]=='8')
{
    cout<<'.';
}
else
{
    cout<<boardArray[i][j];
}

打开包装后可能会更清楚一些

cout<<(((i>9)&&(j<2))?" ":"  ")<<((boardArray[i][j]=='8')?'.':boardArray[i][j]);

会变成这样:

if(i > 9 && j < 2) {
    std::cout << " "; // One space
}
else {
    std::cout << "  "; // Two spaces
}

if(boardArray[i][j] == '8') {
    std::cout << '.';
}
else {
    std::cout << boardArray[i][j];
}

第一部分(用一个或两个空格填充字符串)可以替换为std::setw()

第二部分只是在应该打印 8 时打印 .

具体原因尚不清楚。

ternary 运算符始终可以用 if-else 语句替换。尽管反之通常并非如此。

三元运算符的工作方式是,评估 ? 之前的表达式,如果它是 true 则表达式 before : 被评估,否则,表达式 after 被评估 :

在您的示例中,使用 if-else 的等效代码如下所示:

if ((i>9)&&(j<2))
  cout << " ";
else 
  cout << "  ";

if (boardArray[i][j]=='8')
  cout << ".";
else
  cout << boardArray[i][j];

这些是等价的,选择哪一个取决于你觉得哪一个更具可读性。