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);
}
}
Related
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.
Now if you run this it does not output each Console.WriteLine in one line, why?
I know console.writeline goes to next line when done but the problem is it jumps to next line while printing when it print the exception var it is not in the same line as the rest of the writeline
The error occurs inside the Display() function at the number 6 variable (exception) it is not in the same line as the rest of the writeline, why?
And also there are no line breaks where the error ocurs.
Ans can be any number you like.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace EquationSolver
{
class Program
{
public static string exception = "No Solution Found yet";
public static int go = 40;
public static Decimal x = 0, formul = 0;
public static Decimal pref = -100000, next = 100000,ans;
public static Decimal stepval = next / 10;
public static Decimal prefrem = 1234567890123.1234567890m, nextrem = 1234567890123.1234567890m;
public static Decimal nextremfirst = 0;
public static void Answer()
{
Console.WriteLine("Enter ans");
ans = (Convert.ToDecimal(Console.ReadLine()));
}
public static void Main(string[] args)
{
//Console.WriteLine("Enter ans");
//Answer(Convert.ToDecimal(Console.ReadLine()));
Answer();
//Console.Clear();
while (true)
{
for (var i = 0; i <= go; i++)
{
for (x = pref; x <= next; x += stepval)
{
formul = x;
if (formul < ans)
prefrem = x;
else if (formul > ans)
{
if (nextremfirst == 0)
{
nextrem = x;
nextremfirst += 2;
}
}
else if (formul == ans)
{
AnsFound();
break;
}
else
{
Error();
}
Display();
}
if (formul == ans)
{
AnsFound();
break;
}
if (prefrem != 1234567890123.1234567890m)
pref = prefrem;
if (nextrem != 1234567890123.1234567890m)
next = nextrem;
nextremfirst = 0;
stepval /= 10;
if (formul != ans)
NoAnsyet();
//Console.WriteLine();
}
Finnish();
}
}
public static void Display()
{
//Console.ReadKey();
//Console.WriteLine("Formul: {0} x: {1} Ans: {2} Status: {3}", //formul, x, ans, exception);
//Here is the error:
Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",pref,next,stepval,formul,x,ans,exception);
}
public static void Finnish()
{
if (formul != ans)
Error();
exception = "\ncomplete";
Console.WriteLine(exception);
pref = -100000;
next = 100000;
stepval = next /= 10;
Console.ReadKey();
Console.Clear();
//Console.WriteLine("Enter ans:");
//Answer(Convert.ToDecimal(Console.ReadLine()));
Answer();
}
public static void AnsFound()
{
exception = "\nSolution Found!";
//Console.WriteLine("x: {0} Ans: {1} Status: {2}", x, ans, exception);
//Console.WriteLine("Pref:{0} Next: {1} Stepval: {2} Formul:{3} x:{4} Ans:{5} Status:{}", pref, next, stepval, formul, x, ans, exception);
}
public static void NoAnsyet()
{
exception = "\nNo Solution yet...";
//Console.WriteLine(exception);
}
public static void Error()
{
exception = "\nNo Solution error!!";
Console.WriteLine(exception);
}
}
}
Because you set exception = "\ncomplete"; at different places. The \n at the beginning is a new line character.
Remove the \n
exception = "complete";
Same problem with other texts like "\nSolution Found!".
Using string interpolation makes string formatting more readable:
Replace
Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",
pref, next, stepval, formul, x, ans, exception);
by
Console.WriteLine(
$"Pref:{pref} Next:{next} Step:{stepval} Formul:{formul} x:{x} Ans:{ans} Status:{exception}");
WriteLine writes in a New Line. You should try
Console.Write()
If you want to print right after your previous print.
The value to your variable exception is the reason why the console is printing on a different basically if you put a special character \n means new line hence all the methods you are calling have this special character.
Solution remove special characters and use the Console.WriteLine or Console.Write methods
As per the code provided you have not called the method i made some changes to the code
Edited code
and try to run the code status :No solution found yet
Thanks
Good Day
If this is the output of the Console:
.
.
.
.
Hello World!
I would like to set the cursor's position, say 20 lines from the last line of text. How would I do this in the case that the last line is obviously constantly changing?
Thank you for your time.
Console.SetCursorPosition(Console.CursorLeft, (Console.CursorTop+20))
Passing CursorLeft keeps it at the same left position, if that's important to you. Otherwise you can just pass 0.
Console.SetCursorPosition(0, (Console.CursorTop+20))
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace CUrsorPosition
{
class Program
{
static int lastCursorLocation = 0;
//customCursorPosition say which line number you want the cursor to //set after the last text for example i have set it to 1 so next line to hellow //world
static int customCursorPosition = 1;
static void Main(string[] args)
{
// int customCursorPosition = 0;
WriteLine(".");
WriteLine(".");
WriteLine(".");
WriteLine(".");
int x = Console.CursorLeft;
int y = Console.CursorTop;
Console.CursorTop = Console.WindowTop + Console.WindowHeight - 1;
Console.SetCursorPosition(x, y);
WriteLine("Hello World");
Console.SetCursorPosition(0, y+ customCursorPosition);
Console.ReadLine();
}
static void WriteLine(string message, [CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine(lineNumber + ": " + message);
}
static void WriteLine(string message)
{
StackFrame callStack = new StackFrame(1, true);
var lineNumber = callStack.GetFileLineNumber();
lastCursorLocation = callStack.GetFileLineNumber();
Console.WriteLine(message);
}
}
}
I could not find anything but the program includes five serious errors and some line placement faults. What are the faults? Thank you for your help
using System;
class Program
{
static void Main(string[] args)
{
int deger1, deger2;
deger2 = Convert.ToInt32(Console.ReadLine());
for (kivir =0; kivir <2; kivir++)
{
if (deger1 == 56)
Console.WriteLine(Ekle(kivir, deger1));
deger2--;
else deger1 = 56;
}
}
static int Ekle(int deger1, int deger2)
{
return deger1 + deger2;
}
}
kivir is not declared as a variable.
your if statement appears to have multiple statements but is missing blocks ({...}).
deger1 is not initialized
This version can compile:
using System;
class Program
{
static void Main(string[] args)
{
int deger1 = 0, deger2;
deger2 = Convert.ToInt32(Console.ReadLine());
for (int kivir =0; kivir <2; kivir++)
{
if (deger1 == 56)
{
Console.WriteLine(Ekle(kivir, deger1));
deger2--;
}
else
{
deger1 = 56;
}
}
}
static int Ekle(int deger1, int deger2)
{
return deger1 + deger2;
}
}
However, it will close the console window before you can see the output. You need to add one more Console.ReadLine() before the end of the main method.
I found one error to,there isn't a namespace.
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.