查询有关C ++中的格式输出

时间:2014-06-03 17:00:57

标签: 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(),但它没有给我输出对齐,因为我的左侧文本是不同的。

3 个答案:

答案 0 :(得分:2)

另一个依赖于纯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;
}

答案 1 :(得分:-2)

printf( "%-20s%-20s", "name", "aabsd" );
printf( "%-20s%-20d", "Size in KB", 170 );
printf( "%-20s%-20d %d", "Width and Height", 512, 512 );

-20%s将证明20个空格

20%s将证明20个空格的合理性

答案 2 :(得分:-2)

尝试使用\ t将输出对齐到下一个标签位置。

printf("Name\t%s\n",name);
printf("Size in KB\t%d\n",size);
printf("Width and Height\t%d%d\n",width,height);

这会使第二列对齐,也许你需要在其中一个中使用第二个标签,但就是这样。

另一种方法是手动将光标移动到您想要的位置。这应该

SetCursorPos(xpos,ypos);

您需要包含windows.h

相关问题