Console pause c# - c#

In this code
Console.Write("Enter any number from 0 to 9:");
int k = Console.Read();
Console.Write("The ASCII code for it is:");
Console.WriteLine(k);
Console.Read();
after I input a number my console close instantly.
If I write this code
Console.Write("Enter any string:");
string k = Console.ReadLine();
Console.Write("Your string is:");
Console.WriteLine(k);
Console.Read();
my console stops so I can see what I wrote.
Why is that happening?

Try using the following instead of Console.ReadLine();
Console.ReadKey();
This will wait for your console to input any key before closing.

ReadLine, Read etc. should work but you can also run it via Ctrl-F5 instead, which will keep the window open until you hit a key. Or remove the ReadLine at the end completely if you just want it to close.
Note Ctrl-F5 is running without debugging. If you're after breakpoints don't do this.
Although with your code you're only going to going to get the behaviour you expect from the .Read on line 2.
num=Console.Read();
I think it will be the ASCII code for the first 'character' of your number i.e. if you enter 322 it will just read 3 and the ASCII for 3 is 51, which will be what is assigned to num.

Related

Why do I get System.String [ ] in my code while debugging?

I am on my final project in c# for beginners, but I can't seem to get my list to work properly. It also closes automatically after being 'filled' with orders.
class Burgare
{
private string[] hamburger = new string[24];
private int no_burger = 0;
public void add_burger()//Ordering of burgers
{
Console.Clear(); //Clears console to make it look cleaner
while (true)
{
int Burger_option = 0;
do
{
Console.WriteLine("");// The options user can choose from
Console.WriteLine("Please choose burgers from our menu:");
Console.WriteLine("-------Burgers--------");
Console.WriteLine("1 Original One 109");
Console.WriteLine("2 Pig & Cow 109");
Console.WriteLine("3 Spice & Nice 109");
Console.WriteLine("4 Green One 109");
Console.WriteLine("0 Go back to main menu");
Console.WriteLine("----------------------");
Console.WriteLine("");
try //Making sure the user only picks what is on the menu
{
Burger_option = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("You can only choose what is on the menu!");
}
switch (Burger_option) //Depending on the number user presses on keyboard different burgers will be added to order
{
case 1:
Console.WriteLine("You've added the Original One to your order");
Console.WriteLine("If you're done press 0 to go back to the main menu");
hamburger[no_burger] = "Original One";
break;
case 2:
Console.WriteLine("You've added the Pig & Cow to your order");
Console.WriteLine("If you're done press 0 to go back to the main menu");
hamburger[no_burger] = "Pig & Cow";
break;
case 3:
Console.WriteLine("You've added the Spice & Nice to your order");
Console.WriteLine("If you're done press 0 to go back to the main menu");
hamburger[no_burger] = "Spice & Nice";
break;
case 4:
Console.WriteLine("You've added the Green One to your order");
Console.WriteLine("If you're done press 0 to go back to the main menu");
hamburger[no_burger] = "Green One";
break;
case 0: //Sends user back to main menu
Run();
break;
}
no_burger++; //Adds burger
} while (no_burger != 0);
if (no_burger <= 25) //Maximum number of orders
{
Console.WriteLine("The restaurant can't take more than 24 orders of burgers at the time");
Run(); //Sends user back to main menu when the order is over 24
}
}
}
public void print_order()
{
Console.WriteLine("-Your current order-");
foreach (var burger in hamburger) //Showing a list of what is in the order
{
Console.WriteLine(hamburger);
if (burger != null)
Console.WriteLine(burger);
else
Console.WriteLine("Empty space"); //Making empty space to show where you can add more burgers
}
}
After entering 24 orders I get the error "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" I've looked around a bit but still don't really understand how to fix my code. I'd like for it to return to the main menu after telling the user the order is full.
For my second problem the System.String [] problem, it appears when I enter the 'print_order'. It shows itself as
System.String []
Empty space
System.String []
Empty space
And so on. If possible I'd like to either remove it completely or at least replace it with 1,2,3...etc.
First off, please only post one question per question; you've described many problems here, but only actually asked one question. If you have multiple questions, post multiple questions.
Why do I get System.String[] in my code while debugging?
C# by default gives the name of the type when you print it out, and you're printing an array of strings. To turn an array of strings into a string, use the Join method of the string type. Be careful to not confuse it with the Join extension method on sequences.
It also closes automatically after being 'filled' with orders.
When a console program's control reaches the end of Main, it terminates the program. If you want something else to happen, write code that indicates what you'd like to happen.
After entering 24 orders I get the error "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" I've looked around a bit but still don't really understand how to fix my code. I'd like for it to return to the main menu after telling the user the order is full.
You've reserved space for 24 things, and you've tried to access the 25th thing. That's a fatal error. Don't do that. You are required to detect that situation and prevent it.
If you want it to return to the main menu after telling the user the order is full then write code to do that. How? Since apparently the main menu is a thing that can happen more than once, you'll want to put it in a loop. You've already written two loops; put more stuff in the loops!
While we're looking at your code, some more good advice:
Start using the conventions of the C# language now. You wrote Console.WriteLine and then made a method print_order. Follow the pattern set by the designers of the framework, not something you've just made up on your own. Types and methods should be CasedLikeThis.
Never put an int.Parse in a try-catch, ever. That's what int.TryParse is for!
Your program has a bug; what happens if someone types in, say, 7? Handle that case!
You never actually check to see how many items you've added inside your do...while loop - you only check this after the loop is complete. That's why it crashes when you try to add the 25th item.
Move the logic to handle this inside your do...while loop and you won't get the exception anymore.
Also, your array only has room for 24 items, but I assume that you meant for it to be 25.
Also, since you're new to programming, you may want to look at #Eric Lppert's helpful article on debugging techniques - it'll save you a lot of time. You should also read about how to use a step debugger to diagnose problems.

Is this behavior due to possible async?

Salutations,
I am fairly new to C#, I feel comfortable with Java, and thus I feel decently comfortable with C# (massive fan of its LINQ and SQL syntax). Anywho, I am however a total novice to asynchronous calls, and I was wondering if the following behavior is related to this.
So in my code I have the following:
string sentence;
Console.WriteLine("Enter your sentence: {0}", sentence = Console.ReadLine());
Console.WriteLine("Sentence is: {0}", sentence);
Console.ReadKey();
It is very simple, I was just trying to see if I could insert the reading of the input within the same prompt that asks for it. However, what I notice is that the code runs, but it is a blank screen, I can type my input and then it would display what I typed, and wait for a key click in order to close the CMD window.
What I was wondering is the following: Is this a sort of async behavior -- if not, what is it then? And if so, is it possible to have the ReadLine() within the same Console.WriteLine() or do I have to have them as two separate lines as one would normally do?
There is nothing about asynchronous here.
The first Console.WriteLine requires its parameter(s) to get ready before its own execution. In other words, Console.ReadLine has to execute before the first Console.WriteLine. That is where the blank screen come from.
Just write as
Console.WriteLine("Enter your sentence: ");
sentence = Console.ReadLine()
Console.WriteLine("Sentence is: {0}", sentence);
or in "the same line"
Console.WriteLine("Enter your sentence: ");
Console.WriteLine("Sentence is: {0}", Console.ReadLine());
Synchronous and Asynchronous is not the concern here, just syntax error try
Console.WriteLine("Enter your sentence: ");
Console.WriteLine("Sentence is: {0}", Console.ReadLine());

Console Application - WriteLine above current working line

I have seen a few other posts very similar to this one, but the answers they give are not correctly answering the question. Sorry if there is something hidden away that I couldnt find...
I want to use Console.WriteLine() to print something above my current Console.ReadLine(), for example, my app prints "Hello world" and starts a thread that (in 5 seconds) will print "I just waited 5 seconds" above the line where I need to input something, like this:
Hello world
Please input something: _
Then 5 seconds will pass and it will look like this:
Hello world
I just waited 5 seconds
Please input something: _
So far I've tried using Console.SetCursorPosition(0,Console.CursorTop - 1) but this just prints over the line "Please input something: _" and if I use Console.CursorTop - 2 instead it crashes saying "[2] Out of range" (no idea why this is) and if I use Console.CursorTop - 2 it prints under "Please input something: _"... so my question is how do I print something ABOVE the line "Please input something: _"
Just moving the cursor is not good enough, the problem is that you are inserting text. That is possible, the Console.MoveBufferArea() method gives you access to the underlying screen buffer of the console and lets you move text and attributes to another line.
There are a couple of tricky corner-cases. One you already found, you have to force the console to scroll if the cursor is located at the end of the buffer. And the timer is a very difficult problem to solve, you can only really do this correctly if you can prevent Console.ReadLine() from moving the cursor at the exact same time that the timer's Elapsed event inserts the text. That requires a lock, you cannot insert a lock in Console.ReadLine().
Some sample code you can play with to get you there:
static string TimedReadline(string prompt, int seconds) {
int y = Console.CursorTop;
// Force a scroll if we're at the end of the buffer
if (y == Console.BufferHeight - 1) {
Console.WriteLine();
Console.SetCursorPosition(0, --y);
}
// Setup the timer
using (var tmr = new System.Timers.Timer(1000 * seconds)) {
tmr.AutoReset = false;
tmr.Elapsed += (s, e) => {
if (Console.CursorTop != y) return;
int x = Cursor.Left;
Console.MoveBufferArea(0, y, Console.WindowWidth, 1, 0, y + 1);
Console.SetCursorPosition(0, y);
Console.Write("I just waited {0} seconds", seconds);
Console.SetCursorPosition(x, y + 1);
};
tmr.Enabled = true;
// Write the prompt and obtain the user's input
Console.Write(prompt);
return Console.ReadLine();
}
}
Sample usage:
static void Main(string[] args) {
for (int ix = 0; ix < Console.BufferHeight; ++ix) Console.WriteLine("Hello world");
var input = TimedReadline("Please input something: ", 2);
}
Note the test on the Console.Top property, it ensures that nothing goes drastically wrong when the user typed too much text and forced a scroll or if Console.ReadLine() completed at the exact same time that the timer ticked. Proving that it is thread-safe in all possible cases is hard to do, there will surely be trouble when Console.ReadLine() moves the cursor horizontally at the exact same time that the Elapsed event handler runs. I recommend you write your own Console.ReadLine() method so you can insert the lock and feel confident it is always safe.
You can use carriage-return (\r, or U+000D) to return the cursor to the start of the current line, and then overwrite what's there. Something like
// A bunch of spaces to clear the previous output
Console.Write("\r ");
Console.WriteLine("\rI just waited 5 seconds");
Console.Write("Please input something: ");
However, if the user has started typing already this won't work anymore (as you may not overwrite all they have typed, and they will lose what they've typed on the screen, although it's still there in memory.
To properly solve this you actually need to modify the console's character buffer. You have to move everything above the current line one line up, and then insert your message. You can use Console.MoveBufferArea to move an area up. Then you need to save the current cursor position, move the cursor to the start of the line above, write your message, and reset the cursor position again to the saved one.
And then you have to hope that the user doesn't type while you're writing your message, because that would mess things up. I'm not sure you can solve that while using ReadLine, though, as you cannot temporarily lock something while ReadLine is active. To properly solve that you may have to write your own ReadLine alternative that reads individual keypresses and will lock on a common object when writing the resulting character to avoid having two threads writing to the console at the same time.

C# Console Application Individual Line Loading

I'm currently working in C# in visual studio 2010. I am working on console applications and was wondering if anyone knew a way to have Console.WriteLines appear on the console individually without key strokes? E.g. text that appears line by line. I've looked around quite a bit and can't seem to find a way to do it without using standard command lines rather than C#.
Thanks in advance.
For each string you want on its own line, write that string to the console.
string a = "hello";
string b = "world";
Console.WriteLine(a);
Console.WriteLine(b);
Try to put
Console.ReadKey()
between your line outputs. This will wait for any key to be pressed after every line.
Example:
Console.Write("Press any key to continue ...");
Console.ReadKey(true);
Console.WriteLine("DONE!")
This will print "Press any key to continue ..." then wait for any keystroke and add "DONE!" to the end of the line.
Thanks to everyone who replied, sorry it look my a long time to get back to this, I've been extremely busy. Sorry that my question was poorly phrased. What I was attempting to do was create an image with console.WriteLine();
I found that the way to do this was with system threading to create a delay between lines.

Console.Read is being ignored [duplicate]

This question already has answers here:
Console.Read not returning my int32 [duplicate]
(7 answers)
Closed 1 year ago.
I'm new to the C# language, and have only started learning it for use on the XNA Game Studio for X-box.
I have some minor experience with Java and C++, so I'm not a TOTAL noob. That's exactly why this problem is so frustrating to me.
I have created a simple code designed to add two numbers input from the user. Extremely simple stuff, but a good first step for any new language I feel.
I've declared my variables, and was trying to use Console.Read() to get numbers from the user to add. So far, the code outputs the message I want, then stops and reads in a single input from the user. After that, it messes up. The console outputs the next message, reads some random number (no input), then adds them together and outputs that instantly.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Add
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the first number to add: ");
int firstNumber = Console.Read();
Console.WriteLine("Please enter the second number to add: ");
int secondNumber = Console.Read();
int Sum = firstNumber + secondNumber;
Console.WriteLine("The total of the two numbers is: " + Sum);
}
}
}
Sample runs:
Please enter the first number to add:
2
Please enter the second number to add:
The total of the two numbers is: 63
Please enter the first number to add:
3
Please enter the second number to add:
The total of the two numbers is: 64
It continues like that, acting as though the secondNumber is 61.
Thanks in advance for any help!
That's because it is reading the next character from the console and then converting it to int, which gives the ASCII value, not the numeric value. So typing 2 will be interpreted as the character '2', with the ascii code 50. Try this instead:
int firstNumber = Int32.Parse(Console.ReadLine());
Console.Read reads a single character. So when you enter "2" and hit Enter, you're supplying (1) the character '2', whose ASCII value is 50, and then (2) the carriage-return character, whose ASCII value is 13. The sum of these is ... 63. :-)
In addition to what Gareth said, maybe the MSDN information will clear up to you why it's not waiting for your input on the second Console.Read() method:
Console.Read()
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). Subsequent calls to the Read method retrieve your input one character at a time. After the final character is retrieved, Read blocks its return again and the cycle repeats.
So, on your first Read() it's happily allowing you to enter whatever you want until you hit Enter
Then, it gets to the second Console.Read() and says, "Hey, I already have those characters from the first Console.Read() to go through. It just happens that the second one is whitespace (the carriage return)" and it assigns that whitespace ASCII value to secondNumber.
The problem is that Console.Read() reads the first Return keypress and sends that to the second Console.Read() call. Your code should use ReadLine() instead and look something like this:
Console.WriteLine("Please enter the first number to add: ");
int firstNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second number to add: ");
int secondNumber = Convert.ToInt32(Console.ReadLine());
Console.Read reads a single character from the input block. If you enter a number and then press the enter key it will read the enter key, or the next digit of the first number you entered.
You will likely want to use Console.ReadLine instead.
I think you want the Console.ReadLine() Method
You should Try Console.ReadLine();
You probably want ReadLine not Read as Read takes the next character in the stream, but ReadLine will wait for the user to press enter.
This would cause a bug if your user type 34 the first time, because firstNumber equal 3 not 34.

Categories