C# "scanf" with Custom Console - c#

My program is a Windows Form Application in C#.
I have an interpreter/compiler IDE w/c basically runs a custom Language through a customized console window.
When interpreting input lines like "scanf", how do pause the interpreting while the user doesn't press enter?
Sample custom code to parse:
1 VAR x AS INT
2 START
3 INPUT: x
4 OUTPUT: x
5 STOP
For example, in those lines, when my program processes line 3, it doesn't process the other lines until the user inputs something and presses enter.
Pseudo-Snippet for line by line parsing:
foreach (string line in inputCode)
{
LineType lineType = line.getType();
if(lineType.InputStatement)
{
//wait for input here
}
else if(lineType.OutputStatement)
{
//analyze output code here
}
else if(lineType.AssignmentStatement)
{
//do Evaluation here
}
}

Console.Readline or Console.ReadKey will allow you to read input from the console simillar to scanf.

You should make each method raise an event to fire the next line.
The INPUT method should fire that event after the user presses enter.

Related

How can i keep code that has Thread.Sleep() in it open when it finishes?

I've been trying to make an application that print characters one by one like in old rps. I found out that i need to use Thread.Sleep to do that. I also want the code to stay open instead of closing. Is there any way to do that?
I used Console.Read, Console.ReadLine, and Console.ReadKey. but all of them stop printing what i want after the first character.
{
static void Main(string[] args)
{
string sntnc = "Example";
foreach (char chrctr in sntnc)
{
Console.Write(chrctr);
Thread.Sleep(50)
;
I want the result to be an application that prints character individually and for it to stay open when it finished.
Try the following. When you are inside the foreach loop, your code will keep running and keep your console window open. After the foreach loop, you can call Console.ReadKey(); to keep the console open until a key is pressed. This code will print out the characters one by one with a 50 ms delay between each letter.
public static void Main()
{
string sntnc = "Example";
foreach (char chrctr in sntnc)
{
Console.Write(chrctr);
System.Threading.Thread.Sleep(50);
}
Console.ReadKey();
}

React to keypress during text output in Console application

I am writing a text adventure in c# for a school assignment and I've already come across a problem.
I made a function to type out sentences like this:
public static void Zin (string zin)
{
foreach (char c in zin)
{
Console.Write(c);
Thread.Sleep(50);
}
Now this works but I want to implement that when the player hits the enter key, the sentence is typed out on the console instantly.
I'm not sure how to do this. I've tried using a while loop in the foreach loop that checks wether enter is being hit and then print out the sentence but that doesn't work.
Thanks in advance!
You can use the Console.KeyAvailable property to find out whether keys have been pressed that have not been read via any of the Console.Read* methods.
When keys have been pressed, skip the waiting within the loop. After the loop, read all keys that have been pressed during the loop, so that they will not be returned when you use Console.Read* later on.
public static void Zin(string zin)
{
foreach (char c in zin)
{
Console.Write(c);
// Only wait when no key has been pressed
if (!Console.KeyAvailable)
{
Thread.Sleep(50);
}
}
// When keys have been pressed during our string output, read all of them, so they are not used for the following input
while (Console.KeyAvailable)
{
Console.ReadKey(true);
}
}
See also Listen for key press in .NET console app

Want to conditionally change Console foreground color based on input

I'm trying to make a KeyDown statement work. So I'm writing:
private void KeyDown(object sender, System.Windows.Forms.KeyEventArgs e);
System.Windows.Forms won't work I read that its a Visual Studio Code thing you have to go to Project.json and add System.Windows.Forms as a dependency. I don't know what to write to add it. I searched the web and searched stock overflow. I can't find anything.
I don't know what to type in to add it.
I could be wrong, but I don't believe you can use the System.Windows.Forms assembly with a .Net Core project. My Visual Studio is acting up so I wasn't able to try using it via the project.json imports feature. Having said that, it wouldn't provide you with what you want anyway.
Since you are wanting to capture the input from the user, via the console, and change the color based on some conditions - you'll have to do that manually yourself.
The following is a complete application example that shows how to do that. Essentially you have to evaluate each character entered into the console and determine if it's a number. If it is a number, you have to move the cursor back 1 position so you can overwrite the value that was just entered. Prior to overwriting the value, you change the consoles foreground color.
using System;
namespace ConsoleApp2
{
public class Program
{
public static void Main(string[] args)
{
// Set up an infinite loop that will allow us to forever type unless 'Q' is pressed.
while(true)
{
ConsoleKeyInfo pressedKey = Console.ReadKey();
// If Q is pressed, we quit the app by ending the loop.
if (pressedKey.Key == ConsoleKey.Q)
{
break;
}
// Handle the pressed key character.
OnKeyDown(pressedKey.KeyChar);
}
}
private static void OnKeyDown(char key)
{
int number;
// Try to parse the key into a number.
// If it fails to parse, then we abort and listen for the next key.
// It will fail if anything other than a number was entered since integers can only store whole numbers.
if (!int.TryParse(key.ToString(), out number))
{
return;
}
// If we get here, then the user entered a number.
// Apply our logic for handling numbers
ChangeColorOfPreviousCharacters(ConsoleColor.Green, key.ToString());
}
private static void ChangeColorOfPreviousCharacters(ConsoleColor color, string originalValue)
{
// Store the original foreground color of the text so we can revert back to it later.
ConsoleColor originalColor = Console.ForegroundColor;
// Move the cursor on the console to the left 1 character so we overwrite the character previously entered
// with a new character that has the updated foreground color applied.
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.ForegroundColor = color;
// Re-write the original character back out, now with the "Green" color.
Console.Write(originalValue);
// Reset the consoles foreground color back to what ever it was originally. In this case, white.
Console.ForegroundColor = originalColor;
}
}
}
The output to the console will look like this:

C# Restarting a console application

I've created a small application that does a small conversion. At the end of the program I've created a method that allows the user to make another calculation if they press 'r'. All I want it to do is if they press r, take them back to the beginning of Main, else terminate program. I do not want to use goto. This is what I've got so far, and the error I'm getting.
http://puu.sh/juBWP/c7c3f7be61.png
I recommend you use another function instead of Main(). Please refer to the code below:
static void Main(string[] args)
{
doSomething();
}
public static void WouldYouLikeToRestart()
{
Console.WriteLine("Press r to restart");
ConsoleKeyInfo input = Console.ReadKey();
Console.WriteLine();
if (input.KeyChar == 'r')
{
doSomething();
}
}
public static void doSomething()
{
Console.WriteLine("Do Something");
WouldYouLikeToRestart();
}
A while loop would be a good fit, but since you say the program should run and then give the user the option to run again, an even better loop would be a Do While. The difference between while and Do While is that Do While will always run at least once.
string inputStr;
do
{
RunProgram();
Console.WriteLine("Run again?");
inputStr = Console.ReadLine();
} while (inputStr == "y");
TerminateProgram();
In your case, you want to repeat something so of course you should use a while loop. Use a while loop to wrap all your code up like this:
while (true) {
//all your code in the main method.
}
And then you prompt the user to enter 'r' at the end of the loop:
if (Console.ReadLine () != "r") {//this is just an example, you can use whatever method to get the input
break;
}
If the user enters r then the loop continues to do the work. break means to stop executing the stuff in the loop.

How to exit a console application without requiring enter

What would be the best way to exit an application when a user types x without having to hit enter. The current code I am using is this:
Console.WriteLine("\nType x to exit > ");
string test = Console.ReadLine();
while (test != "x")
{
Console.WriteLine("\nType x to exit > ");
test = Console.ReadLine();
}
This will make the user experience better.
You can use Console.ReadKey instead.
Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window.
Console.ReadKey() let you read a single key press. Console.readLine() is waiting for a line termination. Here's the doc for reference:
http://msdn.microsoft.com/en-us/library/471w8d85.aspx
You can read the first character and then if it's not "x", read a line input (and prepend the first char received before).
You could do something like this:
do
{
Console.WriteLine("\nType x to exit > ");
}
while (Console.ReadKey().KeyChar != 'x');

Categories

Resources