C++如何右对齐多条数据

标签 c++ justify

所以我必须向 std::cout 发送一列数据,我还必须在数据周围显示一些字符,例如:

    Plot Points
   (0,0), (2,3) 
(1,10), (12,14)

我必须在列标题的 "Points" 中的字母 "s" 下右对齐最后一个右括号。

我将数据输出如下:

cout << right << setw(12) << "(" << x1 << "," << y1 << "), (" << x2 << "," << y2 << ")";

但是我看到的所有例子似乎都表明正确和setw似乎只影响我发送到cout的下一条数据,所以在这种情况下仅限 "("

有没有办法将所有这些字符和变量组合在一起,使它们在输出列中一起对齐?

我刚刚学习 C++,所以希望有一些我还没有学过的简单解决方案?

最佳答案

Is there any way to group all those characters and variables together to have them all justified together in the column of output?

是的,您可以使用一些辅助函数来构建字符串:

std::string parentized_pair(int x, int y) {
    std::ostringstream oss;
    oss << "(" << x "," << y << ")";
    return oss.str();
}

并在最终输出中使用那个:

cout << right << setw(12) << parentized_pair(x1,y1) 
     << right << setw(12) << parentized_pair(x2,y2);

关于C++如何右对齐多条数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40706786/

相关文章:

html - 如何将文本扩展到与其容器一样宽?

c++ - QTableWidget 中的 Star Delegate

C++ CreateProcess 无法从 Windows 7 上的套接字接收路径 (64)

c++ - 禁用异常和 noexcept()

CSS : text-align:justify doesn't work in textarea for Internet Explorer

r - 数据帧上的 format(..., justify = "left") 是否也会左对齐列名称?

python - 在 Python 中对齐两侧的文本

alignment - 文本对齐 : justify + left

c++ - 如何在 qt 中创建图像比较器?

c++ - 是什么导致此代码中的段错误?