简体   繁体   中英

How to write multiple columns in a loop in c++?

Suppose I have a loop:

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

I want to fill a file with 128 columns (not rows!), so the first column contains numbers from 1 to 8, second from 9 to 16 and so on and so forth.

The simplest way is to make two loops - the first by lines and nested by columns - and then calculate numbers with easy math expression. Eg:

    for(int line = 0; line < 8; line++)
    {
        for( int col = 0; col < 128; col++)
        {
            cout << setw(5) << line + col * 8 + 1;
        }
        cout << endl;
    }

setw() has parameter 5 to make identical width for colums with numbers from 1 to 1024

EDITED:

If you want to use only one for loop and exact as you give in the question, you can use more complicated math expressions. First, let's calculate number of line as (i-1) / 128 (numbers start from 0) and number of column as (i-1) % 128 (numbers from 0 to 127). And now you can make the following loop with additional new-line-conditional output:

    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;
    }

Of course if you want to make file, you should do something with the output - redirect standard output to file or change cout to other stream.

The items for each columns are just 8i to 8i+7. You can write mutiple loops. 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);
  }
}

Explanation: As we need 8 rows so we call function write_in_file 8 times. Each time function write_in_file writes 128 entries in the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM