简体   繁体   中英

Nested loops C++

So I am making a program that will create a square based on the users desired size. My code so far reads the value, prints out the top of the square but i'm getting caught up on how to set up the sides because of a nested loop I've created. The issue here is that I need for the loop to reset it's values every time it exists.

Here's my code so far:

#include <iostream>

using namespace std;

int main(int,char**) {
  int x;
  int z=1;
  int l=0;
  int n=0;
  int q=1;
  int m=0;
  int o=0;
  do{
    cout << "Enter length between 0 and 64 (-1 to exit): ";
    cin >> x;
    if (x>-1&&x<64){
      cout << "+";
      for (;x-2!=n;++n){
        cout << "-";
      }
      cout << "+" << endl;
    }
    else{
      cout << "Length must be between 0 and 64 inclusive, or enter -1 to exit.";
    }
    do {
      cout << "|";
      do {
        //cout << " ";
        //++m;
        //}while (x-2!=m);
        cout << "|" << endl;
        ++o;
      }
      while (x-2!=o);
      ++z;
    }
    while (z!=5);
  }

The commented out portion is where the program is getting caught up at, it seems that when I increment m until it exits the do while loop, it holds onto the value that it was incremented to. I know that a continue statement breaks from the loop and begins a new iteration of the loop but it doesn't seem to want to fit inside the do-while loop even if i create an if statement such as

if (x-2==m){
continue;
}

Any help would be appreciated

Just put m = 0; before the loop.

m = 0;
do {
    cout << ' ';
    ++m;
} while (x-2 != m);

Or use a for loop instead;

for (int m = 0; m != x-2; m++) {
    cout << ' ';
}

This is the more common idiom for repeating something a certain number of times, since you can see all the conditions related to the loop in a single place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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