Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I want that the user must fill in a zip code.The Zip code contains 4 digits if the zip code has more or less digits then the code will indicate an error
C#
    Console.Write("Geef je postcode: ");
    postcode =  Console.ReadLine();


while (int.TryParse(postcode, out))// i want that if the zip code has more or less than 4 digits then it will give the code in the while.
{

    Console.WriteLine("ongeldige postcode");
    Console.WriteLine("Geef je postcode: ");
    postcode = Console.ReadLine();
}


What I have tried:

C#
while (int.TryParse(postcode, out))

but i don't know how to use tryparse.
Posted
Updated 16-Nov-16 3:36am
Comments
[no name] 16-Nov-16 9:35am    
Reading the documentation for the function would tell you how to use TryParse. And TryParse won't tell you if the number if greater or less than some other number, you need to write code for that yourself.
Foothill 16-Nov-16 17:34pm    
To add onto Michael's solution below, the proper use of TryParse in this scenario is to test if the user actually entered a number for the postal code. Int32.TryParse("123D", out parsedValue) will return false and parsedValue will be null while Int32.TryParse("1234", out parsedValue) will return true and parsedValue will be set to 1234.

1 solution

Tryparse attempts a conversion from one type to another, it does not test the length.

postcode is a string so use the .Length to test <> 4.

C#
while (postcode.Length != 4)// i want that if the zip code has more or less than 4 digits then it will give the code in the while.
{
 
    Console.WriteLine("ongeldige postcode");
    Console.WriteLine("Geef je postcode: ");
    postcode = Console.ReadLine();
}
 
Share this answer
 
v3
Comments
akhandafm17 19-Nov-16 5:37am    
thank you,this is easier than tryparse

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900