Allow To Only Input A Number - C#

拜拜、爱过 提交于 2021-01-28 21:29:22

问题


I'm fairly new to C#. I'm trying to make a basic program that converts Degrees in Celsius to Fahrenheit. But here's the catch, I want to make sure that the user inputs only a valid number and no characters or symbols. And if the user inputs, for example 39a,23, the Console asks him to enter the number again.

 Console.WriteLine("Please enter the temperature in Celsius: ");
 double x = Convert.ToDouble(Console.ReadLine());

Also, I've been making other programs, and I've been wondering - do I always have to use "Convert.ToInt/Convert.ToDouble"? or is there a faster way?


回答1:


It would be better you use the method Double.TryParse. This way you will check if the string that user provided can be parsed to a double.

// This is the variable, in which will be stored the temperature.
double temperature;

// Ask the  user input the temperature.
Console.WriteLine("Please enter the temperature in Celsius: ");

// If the given temperature hasn't the right format, 
// ask the user to input it again.
while(!Double.TryParse(Console.ReadLine(), out temperature))
{
    Console.WriteLine("The temperature has not the right format, please enter again the temperature: ");
}

The method Double.TryParse(inputString, out temperature) will return true , if the parsing is successful and false if it isn't.

For more information about the method Double.TryParse please have a look here.



来源:https://stackoverflow.com/questions/24801628/allow-to-only-input-a-number-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!