System I/O and Streams in VB.NET: Part 2

In this article I will explain you about System I/O and Streams in VB.NET.
  • 1951

In my previous Article, the classes OneMem and OneOver have just one integer field each, but OneOver also overrides the ToString method to return the value of the integer field. In the class OneUser, when the WriteLine method is called upon instance F of the OneMem class (which has no implementation of the ToString method), the Object class's ToString method is called. The Object class's ToString method prints the name of the class OneMem. On the other hand, when WriteLine is called on instance B, it uses the overridden ToString method of the OneOver class. In this particular implementation, the ToString method prints the value of the integer field.

There is one more overloaded style of these methods, which takes a format string and three objects as input parameters (although four objects are supported, it is not Common Language Specification compliant). This overloaded method gives you control over the format of the string representation of the objects written to the console.

In the example given below, "The sum of {0} and {1} is {2}" is the format string. The brackets {0}, {1}, and {2} are replaced by the values from the variables, which come after the format string in serial order. Here, {0} is replaced by the value of i, {1} by the value of j, and {2} by the value of z.

Example of Using a Format String

    Public Class FormatOut
        Public Shared Sub Main()
            Dim i As Integer = 10
            Dim j As Integer = 5
            Dim z As Integer = i + j
            Console.Write("The sum of {0} and {1} is {2}", i, j, z)
            'This will print
            'The sum of 10 and 5 is 15
        End Sub

Output of above example


System Input

Console.In, which provides the standard input stream, has two methods for taking input from the console: the Read and ReadLine methods. The Read method reads one character at a time from the console whereas the ReadLine method, as its name suggests, reads a line off the console. Just as in system output, in system input you can also omit the In and use Console.Read/Console.ReadLine instead of Console.In.Read/Console.ReadLine.

The Read method reads a single character and returns an integer value, which represents the Unicode value of the character. The Read method does not return a Unicode value until the line is terminated by pressing the ENTER key. If there are no more characters to be read, it returns -1. Hence, if a user types more characters on the console before pressing ENTER, the first call to the VB.NET Read method returns only the first character; and rest of the characters can be read with subsequent calls of the Read method.

Note: Pressing ENTER actually adds two characters at the end of the line: a carriage return (/r) and a line feed (/n). If you employ a loop using successive calls of the Read method, be sure to read the carriage return and line feed pair (with two additional reads) before the next Read call; otherwise, the next call will return /r instead of the user input.

The ReadLine method returns a string after reading a line from the console. A line ends with the first occurrence of a line terminator, such as /r or /n. In the case of ReadLine, the string returned does not contain the line terminator. If end of input is reached, then a null value is returned.

The example given below, although very simple, highlights some of the important features of system I/O. The purpose of the program is to display the number of words in a string that a user has entered.

Example of Reading Character Input from the Console

Class WordCount
Shared Sub Main()
            Console.WriteLine("Welcome to the Word Count Program")
            Dim con As Boolean = True
                Console.Write("Enter a String :")

                'Read a string from the user
                Dim original As String = Console.ReadLine()

                'Remove any white spaces at the end of the sentence
                Dim trimmed As String = original.Trim()
                Dim sp As Char() = {" "c}

                'Split the string at every occurrence of a white space
                Dim str As String() = trimmed.Split(sp)

                'Print the word count using a formatted string
                Console.WriteLine("The word count is {0} for the string ""{1}"" ", str.Length, original)

                'Leave one line blank on the screen

                'Ask the user if he wants to continue
                Console.Write("Do you want to continue [n]?")

                'Read a single character 'y' or 'n' or 'N'
                Dim ans As Integer = Console.Read()

                'Read the carriage return '/r'
                Dim carriage As Integer = Console.Read()

                'Console.WriteLine("The value of carriage is "+carriage) ;
                'Read the line feed '/n'
                Dim linefeed As Integer = Console.Read()

                'Console.WriteLine("The value of h is "+linefeed) ;//10
                'Check if the user has put 'n' or 'N'
                'We use the Unicode value for the characters 'n' and 'N'
                If ans = 110 OrElse ans = 78 Then
                    'Set the bool variable to false so we exit the loop
                    con = False
            Console.WriteLine("Thank you for using my program !")
            Console.WriteLine("Press Enter to exit")

            'Wait for the user to press Enter to exit
        End Sub

Output of above example

ar 2.gif

The Main method of class WordCount (shown in Listing 6.3) takes a sentence as input from the user. Then it removes any trailing white spaces at the end of the sentence and finally breaks up the sentence into an array of strings using the Split method of the String class. The length of this array denotes the number of words in the sentence on the console.

Next, the user is given an option to continue or quit the program. A single character is read off the console and checked for its value. User input of 'n' or 'N' indicates a need to discontinue the while loop. We then set the condition flag to false, which causes the program to exit the loop.

You might note, as previously mentioned, the use of two Read methods after reading the input for the user to continue. This is due to the fact that the Read method returns when the ENTER key is pressed. Pressing ENTER has two effects: (1) the Read method returns, and (2) a carriage return (/r) and a line feed (/n) are appended to the console. Therefore, you read these two characters from the console input stream before calling the next ReadLine method.

As an aside, here's an observation and a handy tip. Many new programmers wonder why clicking on the console application from Windows Explorer causes the console screen to close quickly before they can see any output on the console screen. The solution to this problem is simple. Just place a ReadLine statement at the end of your code; the next time you run your program, the console screen does not close until ENTER is pressed.


Hope this article would have helped you in understanding System I/O and Streams in VB.NET.


More Articles

© 2019 DotNetHeaven. All rights reserved.