2017-02-23 30 views
-4

我知道如何在C++中绘制矩形,但是我不知道如何在该矩形内部写入 - 或者任何形状。在C++中创建带有文本的形状

int rows = 10, cols = 10; 
for (int x = 0; x<rows; x++) { 
    for (int y = 0; y<cols; y++) { 
     if (x == 0 || x == 9 || y == 0 || y == 9) { 
      cout << "*"; 

     } 

     else { 
      cout << " "; 
     } 
     cout << "Hello"; 
    } 

    cout << endl; 
} 
+0

你忘了问一个问题。 – George

+1

而不是打印“”,打印一些文本,看看会发生什么。 –

+0

调试器。学习使用调试器。调试器将允许您在打印每行时看到它。 –

回答

0

你可以有一个字符串的载体和“画”图像/文本中有:

int rows = 10, cols = 10; 
std::vector<std::string> strs(rows, std::string(cols, ' ')); 
for (int x = 0; x<rows; x++) 
    for (int y = 0; y<cols; y++) 
     if (x == 0 || x == 9 || y == 0 || y == 9) 
      strs[y][x] = '*'; // only issue you have to address row/column not column/row 

std::string text = "foo"; 
strs[rows/2].replace((cols - text.length())/2, text.length(), text); 

for(const auto &str : strs) 
    std::cout << str << std::endl; 

live example

你可能想要去幻想和它包装成类,并添加方法比如放置文字垂直,对角线等

1

如果没有控制台库(如curses或conio),您可能会在控制台窗口中写入x,y秒。 C++ stdout是基于流的,它是为文本输出为电传打字的世界而设计的。虽然您可以通过包含嵌入文本的屏幕,但这几乎是对系统的滥用。

同时,设置一个80 x 25的屏幕缓冲区。然后编写代码将其打印出来。然后,您可以在该缓冲区中输出您选择的x,y字符,然后使用缓冲区打印例程打印整个批次。

相关问题