如何使用循环为 C++ 绘制矩形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11201728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:56:04  来源:igfitidea点击:

How to draw a rectangle for c++ with loops?

c++

提问by user1467995

So i have this code which makes a box, but want to make the corners +, the lengths |, and the widths - . Also want to input a number so you can draw them like cout<<"enter the length number" etc... how would i do that?

所以我有这个代码来制作一个盒子,但想要制作角 +、长度 | 和宽度 - 。还想输入一个数字,这样你就可以像 cout<<"enter the length number" 等一样绘制它们......我该怎么做?

Here is what i have to make a box:

这是我必须做的一个盒子:

#include <iostream.h> 
#include <string.h> 

void main() 
{ 
  for(int z=1; z<=79; z++) 
  { 
    cout << ""; 
  } 

  cout << endl; 

  for(int i=1; i<=5; i++) 
  { 
    cout << ""; 
    for(int j=1; j<=77; j++) 
    { 
      cout << " "; 
    } 

    cout << "" << endl; 
  } 

  for(int y=1; y<=79; y++) 
  { 
    cout << ""; 
  } 

  cout << endl; 
}

回答by Mantas Norvai?a

Draws a rectangle where int heightis the height and int widthis the width

绘制一个矩形,其中int height是高度,int width是宽度

#include <iostream>

void draw_rect(int width,int height) 
{
    using std::cout;
    cout << "+";
    for (int i = 0; i < width - 2; i++)
    {
        cout << "-";
    }
    cout << "+\n";

    for (int i = 0; i < height - 2; i++)
    {
        cout << "|";
        for (int j = 0; j < width - 2; j++)
        {
            cout << " ";
        }
        cout << "|\n";
    }

    cout << "+";
    for (int i = 0; i < width - 2; i++)
    {
        cout << "-";
    }
    cout << "+\n";
}

int main ()
{
    draw_rect(8,6);
    return 0;
}

And for how to get user input read this: Basic C++ IO

关于如何获取用户输入,请阅读: Basic C++ IO

回答by Firefox_

#include <iostream>
using namespace std;

void draw_rect( int width, int height)
{   
int i;  
cout << char(218); 
for (i=0; i<width-2; i++) 
cout << char(196);
cout << char(191) << endl;

for (i=0; i<height-2; i++)
{
cout << char(179);
for (int j=0; j<width-2; j++) 
cout << " ";
cout << char(179) << endl;
}
cout << char(192);

for(i=0; i<width-2; i++)
cout << char(196);
cout << char(217) << endl;
}

int main()
{
draw_rect(20,10);
return 0;
}