简体   繁体   English

如何在c ++中循环编写多个列?

[英]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.我想用 128 列(不是行!)填充一个文件,所以第一列包含从 1 到 8 的数字,第二列包含从 9 到 16 的数字,依此类推。

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 setw()具有参数 5 以使数字从 1 到 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.如果您只想使用一个for循环并且与您在问题中给出的完全一样,您可以使用更复杂的数学表达式。 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).首先,让我们计算行数为(i-1) / 128 (数字从 0 开始)和列数为(i-1) % 128 (数字从 0 到 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.当然,如果你想制作文件,你应该对输出做一些事情 - 将标准输出重定向到文件或将cout更改为其他流。

The items for each columns are just 8i to 8i+7.每列的项目只有 8i 到 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.解释:因为我们需要 8 行,所以我们调用函数 write_in_file 8 次。 Each time function write_in_file writes 128 entries in the file.每次函数 write_in_file 在文件中写入 128 个条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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