C ++多行文本块

时间:2015-11-01 11:08:36

标签: c++ for-loop ascii-art setw

我要创建一种圣诞贺卡,需要包含使用嵌套for循环生成的设计。

输出需要在四个边上都有一个边框,里面有可变文本以及嵌套for循环设计。

有些事情如下:

enter image description here

我尝试使用for循环生成边框,将设计放入其中,但在打印多行设计时出现了问题。

  <Button
    android:id="@+id/dialogButtonClose"
    android:layout_gravity="center"
    .
    .
    />
  <Button
    android:id="@+id/dialogButtonCancel"
    android:layout_gravity="center"
    .
    .
    />

这会将整个边框向下推,因为设计是多线的。

我对这种方法感到有点难过。也许使用#include <iostream> #include <iomanip> using namespace std; int main(){ char tree[10][10]; int i,j; for(i=0; i<7; i++){ for(j=0; j<7; j++){ if(i==0 && j==3){ // cout << '*'; tree[i][j] = '*'; } else if(i==1 && j==3){ // cout << '|'; tree[i][j] = '|'; } else if(i==2 && j==3){ // cout << 'M'; tree[i][j] = 'M'; } else if(i==3 && j>1 && j<5){ // cout << 'A'; tree[i][j] = 'A'; } else if(i==4 && j>0 && j<6){ if(j % 2 == 0){ // cout << 'o'; tree[i][j] = 'o'; } else { // cout << 'A'; tree[i][j] = 'A'; } } else if(i==5){ if(j % 2 == 0){ // cout << 'A'; tree[i][j] = 'A'; } else { // cout << '~'; tree[i][j] = '~'; } } else if(i==6 && j==3){ // cout << "M"; tree[i][j] = 'M'; } else { // cout << ' '; tree[i][j] = ' '; } } tree[i][7] = '\n'; } tree[6][8] = '\0'; for(i=0; i<30; i++){ for(j=0; j<70; j++){ if(i==0 || i==29){ cout << "^"; } else if(j==0 || j==69){ cout << "*"; } int a,b; if(j>=42 && j<50 && i >= 10 && i< 17){ for(a=0; a<7; a++){ for(b=0; b<8; b++){ cout << tree[a][b]; j++; } i++; } } else { cout << " "; } } cout << endl; } return 0; }

2 个答案:

答案 0 :(得分:0)

问题是你增加内循环中的计数器。

尝试这样的事情:

        if (j >= 42 && j<50 && i >= 10 && i< 17) {
            //for (auto a = 0; a<7; a++) {
                //for (auto b = 0; b<8; b++) {
                    cout << tree[i - 10][j -42];
                    //j++;
                //}
                //i++;
            //}
        }

答案 1 :(得分:0)

所以我想出了一个问题的解决方案。

我没有直接打印到stdout,而是将输出存储在2D char数组中。

以下内容将存储边框:

 for(i=0; i<50; i++){
   for(j=0; j<70; j++){
       if(i==0 || j==0 || i==49 || j==69){
          finalOutput[i][j] = '*'; //Just for the sake of an example
       } else {
          finalOutput[i][j] = ' ';
       }
   }
 }

以下内容将树存放在方框内的某个位置,

 for(i=30; i<7; i++){
    for(j=30; j<7; j++){
       finalOutput[i][j] = tree[i-30][j-30];
    }
 }

然后打印finalOutput解决了我的问题。