-2

I was trying to figure out how to make an infinite loop to verify that a user input was a string. I however found out that when I would test the program by entering a number, the console would deem the string as an input. How do you rectify this?

Btw here is the code I was working on:

 Dim input As Object

        Do
            Try
                input = Console.ReadLine()
            Catch
                Console.WriteLine("Error - Input was Invalid")
                input = Console.ReadLine()
            End Try
        Loop Until TypeOf input Is String
Stephen
  • 3
  • 4
  • Strings are nigh-universal. All user input types (integers, reals, dates, etc.) are valid strings. – RBarryYoung May 29 '17 at 16:11
  • 1
    `How does Visual Basic .NET differentiate` - it does not. [Console.ReadLine](https://msdn.microsoft.com/en-us/library/system.console.readline(v=vs.110).aspx) returns a string. – GSerg May 29 '17 at 16:13
  • Possible duplicate of [Reading an integer from user input](https://stackoverflow.com/questions/24443827/reading-an-integer-from-user-input) – Mathieu Guindon May 29 '17 at 16:19
  • @GSerg do you know any way to verify an input as a string. Btw sorry the code I posted was from when i tried to reverse this by verifying integers. – Stephen May 29 '17 at 16:22
  • @Mat'sMug my question is different to that thread because I ideally want the input to be a string hence I do not want to convert it into an integer. I am asking how to verify that the input is a string – Stephen May 29 '17 at 16:36
  • 2
    The input ***is*** a string, you'd know if you bothered reading `ReadLine`'s documentation... – Mathieu Guindon May 29 '17 at 16:37
  • @Mat'sMug you clearly don't get it. I meant if the user enters a integer e.g. 5, is there a way that you can verify that in a way humans would understand. So yes i do understand that it is a string – Stephen May 29 '17 at 16:52
  • 1
    @Stephen ReadLine always return a string. If you want to know if the string is a representation of a number then you can use Integer.TryParse. – the_lotus May 29 '17 at 17:12
  • What you are trying to do is called *input validation*. You should specify exactly what is required for the input to be valid. Would "5 apples" be valid? – Andrew Morton May 29 '17 at 17:12
  • 1
    If the user enters an integer, your code still gets a string. I'm not the one "not getting it", it seems - especially seeing that you've accepted an answer **identical** to the answers in the post I linked to. – Mathieu Guindon May 29 '17 at 17:40

2 Answers2

1

The function Console.ReadLine() will always return a String value (or nothing, that's equal a null in other languages).

So, if you want to convert to Integer you can use:

Convert.ToInt32(Console.ReadLine())

if Console.ReadLine() isn't a integer it'll throw an exception.

1
Dim i As Integer
If Integer.TryParse(Console.ReadLine(),i)
  'Good to go
End If
Mike
  • 419
  • 4
  • 11