c++ - 关于 C++ 格式化输出的查询

标签 c++ format

<分区>

我想在 C++ 中输出如下:

name                   aabsd
Size in KB             170 
Width and Height       512 512

cout<<"\n \t name "<<std::setw(15)<<filename;
cout<<" \n \t Size in KB "<<std::setw(10)<<size;
cout<< " \n \t Width  and Height  "<<std::setw(3)<<width<<" "<<height;

右侧的值应在同一列中对齐。我尝试使用 setw() 但它没有给我输出对齐,因为我的左侧文本不同。

最佳答案

另一个依赖于纯 C++ 特定构造的答案。

#include <iostream>
#include <iomanip>

int main()
{
   char const* filename = "abcd";
   int size = 10;
   double width = 20;
   double height = 30;

   // std::left says align the output to the left when writing the next field
   // set::setw(20) says use 20 characters for the next field.
   std::cout << std::left << std::setw(20) << "name" << filename << std::endl;
   std::cout << std::left << std::setw(20) << "Size in KB" << size << std::endl;
   std::cout << std::left << std::setw(20) << "Width and Height" << width << " " << height << std::endl;

   return 0;
}

关于c++ - 关于 C++ 格式化输出的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020898/

相关文章:

c++ - 为什么 std::sort 和 partial_sort 需要随机访问迭代器?

c++ - 在 C++ 中循环遍历数组的推荐方法是什么?

python - 无法以字符串格式方法更新defaultdict

c# - 如何在 C# 中的 string.Format 中进行对齐?

excel - 删除excel单元格中的一些数字

php - 使用正确的格式插入日期到 mysql 插入 '0000-00-00'

c++ - 非内置类型的 const 值返回函数的用例是什么?

c++ - 可以在 C++ 中使用 dynamic_cast 进行向上转换和向下转换

c++ - 将 Glade 与 CUDA 编译器 (Nvidia Eclipse Nsight) 结合使用 -> 哪个 NVCC 链接器设置?

mysql - 格式和圆形mysql的区别