2015-09-24 12 views
0

假設我有一個循環:如何在C++循環中編寫多個列?

for(int i=1; i<=1024; i++) 

我想,以填補128列(!不是行)的文件,所以第一列包含數字1到8,第二從9到16等和等等。

請幫助

+1

你有沒有嘗試過比'for'行更多的代碼?如果是這樣,請發佈您嘗試過的內容。 –

+0

你甚至會爲你的列使用什麼(不是行)! – redFIVE

回答

0

最簡單的方法就是讓兩個環路 - 第一個由行和列嵌套的 - 然後計算方便數學表達式數字。 如:

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,使相同的寬度與數字colums從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到其他流。

0

每列的項目只是8i到8i + 7。你可以寫多個循環。 for(int i = 0; i< 128;i++) for(int j = 0; j <8;j++) int k = 8* i+ j;

0
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個條目。