-1

I'm trying to draw a rectangle in c++ by using 2 for-loops. Everything is fine except the rectangle isn't drawn correctly. Can somebody give me a tip? thanks a lot!

#include <iostream> #include <stdlib.h> using namespace std; int main(int argc, char *argv[]) { // Variabili int base1, altezza1; cout << "Inserisci base del rettangolo:"; cin >> base1; cout << "Inserisci l'altezza del rettangolo:"; cin >> altezza1; cout << "I dati che hai inserito sono -> " << "Base:" << base1 << " e Altezza:" << altezza1 << endl; // Controllo base e altezza maggiori di zero + scrivo in output il rettangolo con i dati in input if(base1 > 0 && altezza1 > 0) { for(int i = 0; i < base1; i++) { for(int j = 0; j < altezza1; j++) { cout << "#"; } } }else{ cout << "Errore"; } system("PAUSE"); return 0; } 

The output is this:

It should be in rows and columns.

3
  • The error message tells you that "something" is wrong with system("PAUSE"). Have a look at this post: stackoverflow.com/questions/24776262/pause-console-in-c-program Actually, system("PAUSE") tries to call the command PAUSE that is Windows-specific. Commented Oct 24, 2017 at 14:11
  • system("PAUSE") is non portable, works only on windows. Looks like you're on non-windows platform Commented Oct 24, 2017 at 14:13
  • i know that system pause doesn't work on linux ditros. My answer was another but thanks for the reply i really appreciate it. Commented Oct 24, 2017 at 14:16

4 Answers 4

5

Print a new line where appropriate using the new line character \n. In your case that would be after the inner for loop:

for (int i = 0; i < base1; i++) { for (int j = 0; j < altezza1; j++) { std::cout << "#"; } std::cout << '\n'; // <--- here } 
Sign up to request clarification or add additional context in comments.

Comments

1

Add a newline after each row printed as the answer mentioned by ron. And no need to use system("PAUSE")as I think.

for(int j=0;j<altezza1;j++) { cout<<"#"; } cout<<endl; //newline after each row. 

And try to use readable code for all while posting here in SO.

1 Comment

std::endl flushes the stream, never use it by default.
0

you need to output newlines characters ('\n', see the ascii table for more informations) and if the rectangle needs to be empty like:

#### # # #### 

You will need to output spaces too (also the ascii table)

Comments

0

You are never printing a newline character. This will cause all of your output to appear on the same line in the terminal.

You can solve your issue by streaming '\n' to std::cout every time you finish printing a row:

for (int i = 0; i < base1; i++) { for (int j = 0; j < altezza1; j++) { std::cout << "#"; } std::cout << '\n'; } 

Comments