[英]How to write multiple columns in a loop in c++?
假設我有一個循環:
for(int i=1; i<=1024; i++)
我想用 128 列(不是行!)填充一個文件,所以第一列包含從 1 到 8 的數字,第二列包含從 9 到 16 的數字,依此類推。
最簡單的方法是創建兩個循環 - 第一個按行並按列嵌套 - 然后用簡單的數學表達式計算數字。 例如:
for(int line = 0; line < 8; line++)
{
for( int col = 0; col < 128; col++)
{
cout << setw(5) << line + col * 8 + 1;
}
cout << endl;
}
setw()
具有參數 5 以使數字從 1 到 1024 的列具有相同的寬度
編輯:
如果您只想使用一個for
循環並且與您在問題中給出的完全一樣,您可以使用更復雜的數學表達式。 首先,讓我們計算行數為(i-1) / 128
(數字從 0 開始)和列數為(i-1) % 128
(數字從 0 到 127)。 現在您可以使用額外的換行條件輸出進行以下循環:
for(int i=1; i<=1024; i++)
{
cout << setw(5) << ( 1 + 8 * ((i-1) % 128) ) + ( (i-1) / 128 );
if( i % 128 == 0 ) // new line once per 128 numbers
cout << endl;
}
當然,如果你想制作文件,你應該對輸出做一些事情 - 將標准輸出重定向到文件或將cout
更改為其他流。
每列的項目只有 8i 到 8i+7。 您可以編寫多個循環。 for(int i = 0; i< 128;i++) for(int j = 0; j <8;j++) int k = 8* i+ j;
void write_in_file( ofstream &fout, int start){
for(int i = 1; i <= 128; i++){
fout<<start <<"\t";
start+=8;
}
fout<<"\n";
}
int main(){
ofstream fout;
fout.open("out.txt");
for(int i=1;i<=8;i++){
write_in_file(fout,i);
}
}
解釋:因為我們需要 8 行,所以我們調用函數 write_in_file 8 次。 每次函數 write_in_file 在文件中寫入 128 個條目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.