0

this is my simple C# console app in this i will get input from user i have postal code variable in which i want to take input as integer but when i input integer it shows error. another approch is that console.readline take both int and string as input or not ??

namespace ConsoleApplication1
{
  class Program
  {

    static void Main(string[] args)
    {
        string firstname;
        string lastname;
        string birthdate;
        string addressline1;
        string adressline2;
        string city;
        string stateorprovince;
        int    ziporpostalcode;
        string country;        
        ziporpostalcode =int.Parse(Console.ReadLine());          
    }
}
}
2
  • 1
    Just a friendly tip, you may want to read over this page: The How-To-Ask Guide so you can always be sure that your questions are easily answerable and as clear as possible. Be sure to include any efforts you've made to fix the problem you're having, and what happened when you attempted those fixes. Also don't forget to your show code and any error messages! Commented Apr 13, 2016 at 4:18
  • 1
    We can't help you fix an error if they only thing we know about the problem is that, "it shows error". What does that mean? Commented Apr 13, 2016 at 4:18

3 Answers 3

2

you should Use int.TryParse instead for int.Parse, Which is responsible to Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded, else return false(conversion failed)

So your code may looks like this:

int ziporpostalcode;
if (int.TryParse(Console.ReadLine(), out ziporpostalcode))
{
    Console.WriteLine("Thank you for entering Correct ZipCode");
    // now ziporpostalcode will contains the required value
   // Proceed with the value
}
else {
    Console.WriteLine("invalid zipCode");
}
Console.ReadKey(); 
Sign up to request clarification or add additional context in comments.

Comments

0
        Console.WriteLine("Enter Zip Code");
        try
        {
            ziporpostalcode = int.Parse(Console.ReadLine());
            Console.WriteLine("You Enter {0}", ziporpostalcode);
        }
        catch (Exception) {
            Console.WriteLine("Error Occured, Enter only Number");
        }

        Console.ReadLine();

1 Comment

how to make it easy not using a if else condtion or exeption
0

Suggested way.

Use int.TryParse to validate your input to int.

var input =int.Parse(Console.ReadLine());    
if(int.TryParse(input, out ziporpostalcode )
{
    // you have int zipcode here
}
else
{
   // show error. 
}

1 Comment

Ahh... yes, Thanks @un-lucky. fixed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.