我想打印一个包含按列组织的数字的字符串数组。
数组包含{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>
我的代码中的主要问题是下一列始终在上一列结束后的新行中开始。
答案 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::array
或std::vector
来代替那些简单数组,因为它看起来像是要整数数组/矩阵。
#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