完成输出后,控制台应用程序退出..如何让它再次请求输入?

时间:2015-08-18 20:06:28

标签: c++

我在VStudio 2015中创建了一个控制台应用程序....在正确执行后,请求输入并显示输出,然后按任意键继续。 我希望程序再次询问输入... 下面是代码: -

   #include "stdafx.h"
   #include "iostream"
   #include "stdio.h"
   using namespace std;

   int main()
   {
          int a, b, n;
          cout << "Enter the number of lines:";
          cin >> n;
          for (a = 1; a <= n; a++)
          {
                 for (b = 1; b <= a; ++b)
                 {
                           cout << a;
                 }
                 cout << "\n";
          }
   system("pause");
   return 0;
   }

2 个答案:

答案 0 :(得分:1)

添加另一个循环:

int a, b;
int n = 1;
while (n > 0)
{
    cout << "Enter the number of lines:";
    cin >> n;
    for (a = 1; a <= n; a++)
    {
        for (b = 1; b <= a; ++b)
        {
            cout << a;
        }
        cout << "\n";
    }
} 

答案 1 :(得分:-1)

在代码上放置第三个循环。

 int a, b, n;

     while(true)
     {
          // here you need to figure out how to break loop 
          // I mean how to go out from it. It depends on your 
          // purpose 

          cout << "Enter the number of lines:";
          cin >> n;
          if (n==-1)
          {
             // I assume n should be larger than 0 for your purpose.
             break;
          }
            for (a = 1; a <= n; a++)
          {
                 for (b = 1; b <= a; ++b)
                 {
                           cout << a;
                 }
                 cout << "\n";
          }
     }

修改

虽然我认为没必要,但正如你所看到的,有人认为使用n&lt; = 0比n == - 1更好。这是你的电话。您可以更改它,或者只键入一个信息,该信息指出用户应该将哪个数字作为输入来终止程序。