在列c ++中打印数字

时间:2018-06-09 04:28:17

标签: c++ string loops formatting

我想打印一个包含按列组织的数字的字符串数组。

数组包含{2 16 4 1 8 1 3 3 2 }

我想以这种形式打印它们

 2      
 1
 3
        16
        8
        3
                  4
                  1
                  2

我试图这样做,但它打印出来像这样

std::string arr[] = {"2","1","3","16","8","3","4","1","2"};
std::string s="";
int count=0;

for (int i = 0; i <3 ; ++i) 
{
    for (count; count <(i+1)*3 ; ++count) 
    {
        for (int j = 0; j <i ; ++j) 
        {
            std::cout<<"\t";
        }
            std::cout<<arr[count]<<std::endl;
    }
}

任何帮助?

我的代码:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="left" android:right="14.5dp" android:top="14.5dp">
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="line">
            <stroke
                android:width="1dp"
                android:color="#000000"
                android:dashWidth="2dp"
                android:dashGap="1.4dp" />
        </shape>
    </item>
    <item android:gravity="right" android:bottom="14.5dp">
        <rotate
            android:fromDegrees="-45"
            android:toDegrees="0"
            android:pivotX="100%"
            android:pivotY="0%">
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="line">
            <stroke
                android:width="1dp"
                android:color="#000000"
                android:dashWidth="2dp"
                android:dashGap="1.4dp" />
            <size android:width="22.3dp" android:height="22.3dp" />
        </shape>
        </rotate>
    </item>
</layer-list>

我的代码中的主要问题是下一列始终在上一列结束后的新行中开始。

1 个答案:

答案 0 :(得分:1)

  

我想打印一个包含数字的字符串数组   列。该数组包含{"2","1","3","16","8","3","4","1","2"}

     

我想以这种形式打印它们

2       16        4
1       8         1
3       3         2

对于您的给定代码,您可以执行以下更改以获得结果。

  • 使用sizeof(arr)/sizeof(*arr);查找数组长度。
  • 根据矩阵的大小制作循环。这是遍历行。
  • 使用第二个循环,直到达到最大数组长度,打印每个数组元素。索引根据矩阵大小递增。
  • 每次内循环完成打印后进行换行。

PS :使用std::string数组是一个坏主意。您可以使用简单数组std::arraystd::vector来代替那些简单数组,因为它看起来像是要整数数组/矩阵。

请参阅输出 enter image description here

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
   std::string arr[]={"2","1","3","16","8","3","4","1","2"};
   const int arrlength = sizeof(arr)/sizeof(*arr);
   const int matrixSize = 3;

   for(int row = 0; row < matrixSize; ++row)
   {
      for (int index = row; index < arrlength ; index += matrixSize)
         std::cout << arr[index] << std::setw(5);
      std::cout << "\n";
   }

  return 0;
}

输出:

2   16    4    
1    8    1    
3    3    2