简体   繁体   English

嵌套循环 C++

[英]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.注释掉的部分是程序被赶上的地方,似乎当我增加 m 直到它退出 do while 循环时,它会保持它增加到的值。 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我知道 continue 语句从循环中中断并开始循环的新迭代,但它似乎不想适合 do-while 循环,即使我创建了一个 if 语句,例如

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

Any help would be appreciated任何帮助,将不胜感激

Just put m = 0;只要把m = 0; before the loop.在循环之前。

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

Or use a for loop instead;或者改用for循环;

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.这是重复某件事一定次数的更常见的习惯用法,因为您可以在一个地方看到与循环相关的所有条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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