i just need to be able to loop a console app. what i mean by that is:
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.
i hope that made sense. can anyone please explain how i would go about doing this? thank you :)
Console.WriteLine("bla bla - enter xx to exit");
string line;
while((line = Console.ReadLine()) != "xx")
{
string result = DoSomethingWithThis(line);
Console.WriteLine(result);
}
while(true) {
DisplayText();
GetInput();
DoCalculation();
DisplayResult();
DisplayText();
GetInput();
}
The user can stop the program at any point with CTRL-C.
Is this what you meant?
You could wrap the whole body of your Main method in program.cs in a while loop with a condition that will always be satisfied.
E.g (in pseudo-code)
While (true)
{
Body
}
Kindness,
Dan
Use a While loop
bool userWantsToExit = false;
get input
while(!userWantsToExit)
{
do calc;
display results;
display text;
get input;
if (input == "exit")
userWantsToExit = true;
}
program end;
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());
}
}
}
You can just put a loop around whatever you're doing in your program.
Related
I am required to write a program that prints out numbers until I write in the console window a simple string "stop". The numbers are supposed to go on infinitely until the condition is met.
I tried:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
internal class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 1000000000;)
{
Console.WriteLine(i);
string a = Console.ReadLine();
if (a == "stop")
{
break;
}
i++;
}
}
}
}
But, there is a delay waiting for my input every time, it's not constant.
You are asking for a non blocking console read. THats not simple.
One way is to peek to see if a key is available to read
int number = 0;
while (true)
{
Console.WriteLine(number);
number++;
if (Console.KeyAvailable)
{
var s = Console.ReadLine();
if (s == "stop")
break;
}
}
Hi I am trying to make a console app that ask the user repeatedly to input a word until the time expires.
I have manage to use this for display the counter
`
for (int a = 20; a >= 0; a--)
{
Console.Write("\rTIME COUNTDOWN {0:00}", a);
System.Threading.Thread.Sleep(1000);
}`
The console will ask the user to input a word, I want to read the input and then repeat the question and read again input until the time expires.
Console.WriteLine($"insert word");
var input = Console.ReadLine();
How can I achieve this? Any help?
you can use WaitHandle.WaitOne method
the countdown loop will run and the user will enter an input and when the countdown is finished, the score will be printed and the thread will be finished and there will be a signal to print the user score.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static bool flg = true;
static int count = 20;
static void Main()
{
Console.WriteLine($"insert word");
for (int a = 20; a >= 0; a--)
{
//Console.WriteLine("\rTIME COUNTDOWN {0:00}", a);
System.Threading.Thread.Sleep(1000);
count = a;
ThreadPool.QueueUserWorkItem(
new WaitCallback(GetInputFromUser), autoEvent);
}
// Wait for GetInputFromUser method to signal.
autoEvent.WaitOne();
Console.WriteLine("you scored x points");
}
static void GetInputFromUser(object stateInfo)
{
if (Console.KeyAvailable || flg)
{
flg = false;
var input = Console.ReadLine();
Console.WriteLine($"insert word");
}
((AutoResetEvent)stateInfo).Set();
}
}
}
Currently i wanna display the following variable
Total Item
Total Execution
Finish Status
using System;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
int TotalValue = 250; // Total Item Example
int TotalExecution = 0;
bool Finish_Status = false;
for (int i = 0; i < TotalValue; ++i)
{
//Do Work Here
System.Threading.Thread.Sleep(10); // Example Work
TotalExecution++;
if (TotalValue - TotalExecution == 0)
{
Finish_Status = true;
}
Console.Clear();
Console.Write("Progression Info\n Total Item : {0}\n Execution Total : {1}\n Remaining : {2}\n Finish_Status : {3}", TotalValue,TotalExecution, TotalValue - TotalExecution, Finish_Status); // Display Information To Console
}
Console.ReadLine();
}
}
}
The result is good,however i was wondering if theres a much more efficient way of doing this,preferably updating it without using Console.Clear();
You can use Console.SetCursorPosition to move the cursor around the console buffer for each write, rather than clearing the console each time.
For example:
using System;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
int TotalValue = 250; // Total Item Example
int TotalExecution = 0;
bool Finish_Status = false;
Console.Write("Progression Info\n Total Item : \n Execution Total : \n Remaining : \n Finish_Status : ");
for (int i = 0; i < TotalValue; ++i)
{
//Do Work Here
System.Threading.Thread.Sleep(10); // Example Work
TotalExecution++;
if (TotalValue - TotalExecution == 0)
{
Finish_Status = true;
}
Console.SetCursorPosition(26, 1);
Console.Write(TotalValue);
Console.SetCursorPosition(31, 2);
Console.Write(TotalExecution);
Console.SetCursorPosition(25, 3);
Console.Write(TotalValue - TotalExecution);
Console.SetCursorPosition(29, 4);
Console.Write(Finish_Status);
}
Console.ReadLine();
}
}
}
Disclaimer: Obviously the above is quick 'n' dirty, and would benefit from substantial refinement, but you get the idea.
Welcome kepanin_lee
I think you are looking for something like this.
//Console.Clear()
Console.Write(vbCr & "Progression Info\n...
Just start with vbCr, by this way you force to start on the beginning of the same line, so you only overwrite the last line, without clear all the screen.
This is a program with two threads; one for output and one for input. (Where _ is the console cursor)
Please enter a number:
12_
While you're typing 12, output gets generated which clears the current line and writes over it, so this happens:
Please enter a number:
Output
_
How can I make it take the 12 which you're still entering and move it to the next line, so you don't have to retype it?
Thanks in advance.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
Program prog = new Program();
Thread t1 = new Thread(prog.getInput);
t1.Start();
prog.otherThread();
}
public void otherThread()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
ClearCurrentConsoleLine();
Console.WriteLine("Output");
}
}
public void getInput()
{
while (true)
{
string msg;
msg = Console.ReadLine();
}
}
public static void ClearCurrentConsoleLine()
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
for (int i = 0; i < Console.WindowWidth; i++)
{
Console.Write(" ");
}
Console.SetCursorPosition(0, currentLineCursor);
}
}
As you can see, when you enter "Hello" and DON'T enter, after 3 seconds it will be overwritten by "Output". I want to move the "Hello" and the input to the second line before it gets overwritten.
I just found this article (web archive) where Cursor positions and modifications are discussed. I found it pretty straight forward.
The centerpiec of it would be:
int left = Console.CursorLeft;
int top = Console.CursorTop;
Console.SetCursorPosition(15, 20);
If I understood you correctly, this should work.
Make the string msg Global. Declare it outside all functions.
Now simply print it in the next line after you clear the previous line..
class Program
{
string msg;
static void Main(string[] args)
{
Program prog = new Program();
Thread t1 = new Thread(prog.getInput);
t1.Start();
prog.otherThread();
}
public void otherThread()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
ClearCurrentConsoleLine();
Console.WriteLine("Output");
}
}
public void getInput()
{
while (true)
{
msg = Console.ReadLine();
}
}
public static void ClearCurrentConsoleLine()
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
for (int i = 0; i < Console.WindowWidth; i++)
{
Console.Write(" ");
}
Console.SetCursorPosition( 0, currentLineCursor + 1 );
Console.Write(msg);
Console.SetCursorPosition(0, currentLineCursor);
}
}
I'm attempting to work with the Console.ReadKey() function in order to intercept the user's keystrokes and rebuild what they are typing on the screen (as I'll need to clear the screen often, move the cursor often, and this seemed like the most full-proof method of making sure what they typed didn't vanish or appear at random points all over the screen.
My question is: Has anyone else ever experienced a 1 character "lag", for lack of a better term, when doing something similar? Say I want to type the word "This". When I press "T", nothing shows up, no matter how long I wait. When I press "h", the "T" appears. "i", the "h" appears. The letter I type will not appear until I hit another key, even if that key is the space bar. Does anyone have any suggestions for what I am doing wrong? I'm sure it has to do with how I am using Console.Readkey, I just don't see what alternative would work. I have attached a small and simple example of this below.
Thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
private static string userInput = "";
static ConsoleKeyInfo inf;
static StringBuilder input = new StringBuilder();
static void Main(string[] args)
{
Thread tickThread = new Thread(new ThreadStart(DrawScreen));
Thread userThread = new Thread(new ThreadStart(UserEventHandler));
tickThread.Start();
Thread.Sleep(1);
userThread.Start();
Thread.Sleep(20000);
tickThread.Abort();
userThread.Abort();
}
private static void DrawScreen()
{
while (true)
{
Console.Clear();
Console.SetCursorPosition(0, 0);
Console.Write("> " + userInput);
Thread.Sleep(300);
}
}
private static void UserEventHandler()
{
inf = Console.ReadKey(true);
while (true)
{
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
inf = Console.ReadKey(true);
userInput = input.ToString();
}
}
}
}
It is because you have 2 times Console.ReadKey()
If you change your code into this
private static void UserEventHandler()
{
while (true)
{
inf = Console.ReadKey(true);
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
userInput = input.ToString();
}
}
It does not lag. the second Console.ReadKey() is blocking in your code. I did not check if you need the parameter true to the readkey, that's for you to find out