C# 检查用户输入是否为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14304591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:22:31  来源:igfitidea点击:

Check if user input is a number

c#

提问by TBK

I want to check if user's input is a number. If yes I want the function to keep running else want to alert him and run it again.

我想检查用户的输入是否是数字。如果是,我希望该功能继续运行,否则想提醒他并再次运行它。

Console.WriteLine(String.Concat("choose your action" ,Environment.NewLine ,
                                "1.Deposit", Environment.NewLine,
                                "2.Withdraw", Environment.NewLine,
                                "3.CheckAccount"));
string c = Console.ReadLine();
int value = Convert.ToInt32(c);

if (value==char.IsLetterOrDigit(value)) //<----- no good why?
{
    switch (value)
    {
        case 1:
            Deposit();
            return;
        case 2:
            Withdraw();
            return;
        case 3:
            CheckAccount();
            return;
    }
}

采纳答案by Mir

Just use:

只需使用:

string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value)) { /*Operate*/ }

EDIT: to adapt the code to the author's comment:

编辑:使代码适应作者的评论:

if (int.TryParse(c, out value) && value >= 1 && value <= 3) { /*Operate*/ }

回答by alpha

int value = Convert.ToInt32(c); this is going to fail if c is not a string consisting of integers only. use try catch to handle this situation.

int 值 = Convert.ToInt32(c); 如果 c 不是仅由整数组成的字符串,这将失败。使用 try catch 来处理这种情况。