Как зациклить консольное приложение - PullRequest
5 голосов
/ 18 ноября 2009

Мне просто нужно иметь возможность зациклить консольное приложение. под этим я подразумеваю:

program start:
display text
get input
do calculation
display result
display text
get input.

REPEAT PROCESS INFINATE NUMBER OF TIMES UNTIL THE USER EXITS THE APPLICATION.
program end.

Надеюсь, это имело смысл. Может кто-нибудь объяснить, пожалуйста, как я буду делать это? спасибо:)

Ответы [ 6 ]

15 голосов
/ 18 ноября 2009
Console.WriteLine("bla bla - enter xx to exit");
string line;
while((line = Console.ReadLine()) != "xx")
{
  string result = DoSomethingWithThis(line);
  Console.WriteLine(result);
}
6 голосов
/ 18 ноября 2009

Вы можете заключить все тело вашего метода Main в program.cs в цикл while с условием, которое всегда будет выполняться.

Eg (в псевдокоде)

While (true)
{
   Body
}

Доброжелательность,

Dan

6 голосов
/ 18 ноября 2009
while(true) {
  DisplayText();
  GetInput();
  DoCalculation();
  DisplayResult();
  DisplayText();
  GetInput();
}

Пользователь может остановить программу в любой точке с помощью CTRL-C.

Это то, что вы имели в виду?

4 голосов
/ 18 ноября 2009

Использование цикла while

bool userWantsToExit = false;

get input

while(!userWantsToExit)
{

  do calc;
  display results;
  display text;
  get input;
  if (input == "exit") 
    userWantsToExit = true;
}

program end;
3 голосов
/ 19 июля 2016
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace InputLoop
{
    class Program
    {
        static long PrintFPSEveryXMilliseconds = 5000;
        static double LimitFPSTo = 10.0;
        static void Main(string[] args)
        {
            ConsoleKeyInfo Key = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
            long TotalFrameCount = 0;
            long FrameCount = 0;
            double LimitFrameTime = 1000.0 / LimitFPSTo;
            do
            {
                Stopwatch FPSTimer = Stopwatch.StartNew();
                while (!Console.KeyAvailable)
                {
                    //Start of Tick
                    Stopwatch SW = Stopwatch.StartNew();

                    //The Actual Tick
                    Tick();

                    //End of Tick
                    SW.Stop();
                    ++TotalFrameCount;
                    ++FrameCount;
                    if (FPSTimer.ElapsedMilliseconds > PrintFPSEveryXMilliseconds)
                    {
                        FrameCount = PrintFPS(FrameCount, FPSTimer);
                    }
                    if (SW.Elapsed.TotalMilliseconds < LimitFrameTime)
                    {
                        Thread.Sleep(Convert.ToInt32(LimitFrameTime - SW.Elapsed.TotalMilliseconds));
                    }
                    else
                    {
                        Thread.Yield();
                    }
                }
                //Print out and reset current FPS
                FrameCount = PrintFPS(FrameCount, FPSTimer);

                //Read input
                Key = Console.ReadKey();

                //Process input
                ProcessInput(Key);
            } while (Key.Key != ConsoleKey.Escape);
        }

        private static long PrintFPS(long FrameCount, Stopwatch FPSTimer)
        {
            FPSTimer.Stop();
            Console.WriteLine("FPS: {0}", FrameCount / FPSTimer.Elapsed.TotalSeconds);
            //Reset frame count and timer
            FrameCount = 0;
            FPSTimer.Reset();
            FPSTimer.Start();
            return FrameCount;
        }

        public static void Tick()
        {
            Console.Write(".");
        }

        public static void ProcessInput(ConsoleKeyInfo Key)
        {
            Console.WriteLine("Pressed {0} Key", Key.KeyChar.ToString());
        }
    }
}
1 голос
/ 18 ноября 2009

Вы можете просто поставить цикл вокруг того, что вы делаете в своей программе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...