I’ve just started with VB in VS2010 and attempting to write a simple console calculator. However, i can’t get it to wait to display the output. The console window closes immediately even after putting a Console.Read(). I guess the input buffer from my ReadLine() still has some valid characters. I’ll paste the code here:
Sub Main()
Dim num1 As Double
Dim num2 As Double
Dim op As Char
Dim ans As Double
Console.Write("Enter first number:")
num1 = CType(Console.ReadLine(), Double)
Console.Write("Enter second number:")
num2 = CType(Console.ReadLine(), Double)
Console.Write("Enter an operator:")
op = ChrW(Console.Read())
Select Case op
Case "+"
ans = num1 + num2
Console.WriteLine("Result=" + ans.ToString())
Case "-"
ans = num1 - num2
Console.WriteLine("Result=" + ans.ToString())
Case "*"
ans = num1 * num2
Console.WriteLine("Result=" + ans.ToString())
Case "/"
If num2 <> 0 Then
ans = num1 / num2
Console.WriteLine("Result=" + ans.ToString())
Else : Console.WriteLine("Error: Division by zero")
End If
End Select
Console.Read()
End Sub
I’ve noticed that i need to put 3 Console.Read()’s at the end of the code to finally get the console to wait. Why is this happening?
Try adding this to the end and you’ll see what’s happening:
The
Console.Readforopis unblocked when you hit return, but the carriage return/line feed sequence is in the buffer and hasn’t been consumed. So two additionalConsole.Readcalls clear the CR (Dec: 13)/LF (Dec: 10) and then the third blocks like you want.Console.ReadLinedoesn’t work because it consumes the CR/LF and there’s nothing then to block existing the app. TwoConsole.ReadLinecalls orConsole.ReadLinefollowed byConsole.Readwould work.