Results 1 to 4 of 4

Thread: Problems with Console.Read()

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    2

    Problems with Console.Read()

    Hi,

    I am stuck with this very basic problem that I am unable to resolve. Here is a piece of code that I am working on:

    Module Module1
    Sub Main()
    Console.Write("Enter Age, Name Salary: ")
    Age = Console.Read()
    FirstName = Console.Read()
    Salary = Console.ReadLine()
    Console.WriteLine(Age & " " & FirstName & " " & Salary)
    End Sub
    End Module

    At the command prompt I enter the following values

    20 Ann 20000

    and it gives me an InvalidCastException

    Could you explain what kind of input would be suitable to make this run???

  2. #2
    Pro Grammar chris128's Avatar
    Join Date
    Jun 2007
    Location
    England
    Posts
    7,604

    Re: Problems with Console.Read()

    I think Console.Read just reads one single character so when you type 20 and expect that to go into the Age variable, its actually only the 2 that goes in and then 0 probably ends up in the FirstName variable.

    Having said that, that shouldnt cause an InvalidCastException. Are you actually declaring Age, FirstName and Salary anywhere?
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

    Blog: cjwdev.wordpress.com
    Web: www.cjwdev.co.uk


  3. #3

    Thread Starter
    New Member
    Join Date
    Sep 2009
    Posts
    2

    Re: Problems with Console.Read()

    Thanks for replying...

    yes....sorry i forgot to mention....I declare them as Integer, String and Double respectively in the beginning of the code!

    My understanding is that Console.Read() reads characters
    up to the first whitespace character, such as a space or tab.

    But as per the output I think your explanation makes sense...

  4. #4
    Pro Grammar chris128's Avatar
    Join Date
    Jun 2007
    Location
    England
    Posts
    7,604

    Re: Problems with Console.Read()

    Have a read of the MSDN documentation on what it does exactly: http://msdn.microsoft.com/en-us/libr...sole.read.aspx

    I would just use Console.ReadLine all of the time if I were you
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

    Blog: cjwdev.wordpress.com
    Web: www.cjwdev.co.uk


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width