从用户输入中读取整数

Tom*_*omG 67 c# input

我正在寻找的是如何读取用户从命令行(控制台项目)给出的整数.我主要了解C++并且已经开始了C#路径.我知道Console.ReadLine(); 只接受一个字符串/字符串.所以总之我正在寻找这个的整数版本.

只是为了让你了解我正在做的事情:

Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
Run Code Online (Sandbox Code Playgroud)

我一直在寻找这个.我在C上找到了很多但不是C#.我确实在另一个网站上找到了一个建议从char转换为int的线程.我确信必须有比转换更直接的方式.

Cod*_*ned 107

您可以使用Convert.ToInt32()函数将字符串转换为整数

int intTemp = Convert.ToInt32(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,我之前尝试过这个并没有用.但只是再试一次它确实...谢谢Console.WriteLine("1.添加帐户."); Console.WriteLine("输入选项:"); int choice = Convert.ToInt32(Console.ReadLine()); if(choice == 1)//等等.这很有效.将标记为答案. (3认同)
  • 这个答案是完全错误的。如果用户输入不是数字,Convert.ToInt32 或 Int32.Parse 将失败并出现异常。当您无法保证输入是数字时,请始终使用 Int32.TryParse。 (2认同)

Mar*_*rco 55

我建议你使用TryParse:

Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
Run Code Online (Sandbox Code Playgroud)

这样,如果你尝试解析像"1q"或"23e"这样的东西,你的应用程序不会抛出异常,因为有人输入了错误.

Int32.TryParse返回一个布尔值,因此您可以在if语句中使用它,以查看是否需要对代码进行分支:

int number;
if(!Int32.TryParse(input, out number))
{
   //no, not able to parse, repeat, throw exception, use fallback value?
}
Run Code Online (Sandbox Code Playgroud)

对于您的问题:您将找不到读取整数的解决方案,因为ReadLine()读取整个命令行,threfor返回一个字符串.你可以做的是,尝试将此输入转换为int16/32/64变量.

有几种方法:

如果您对要转换的输入有疑问,请始终使用TryParse方法,无论您是尝试解析字符串,int变量还是其他方法.

更新 在C#7.0中,变量可以直接在作为参数传入的位置声明,因此上面的代码可以压缩成:

if(Int32.TryParse(input, out int number))
{
   /* Yes input could be parsed and we can now use number in this code block 
      scope */
}
else 
{
   /* No, input could not be parsed to an integer */
}
Run Code Online (Sandbox Code Playgroud)

一个完整的例子如下所示:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var foo = Console.ReadLine();
        if (int.TryParse(foo, out int number1)) {
            Console.WriteLine($"{number1} is a number");
        }
        else
        {
            Console.WriteLine($"{foo} is not a number");
        }
        Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到,number1即使输入不是数字,变量也会被初始化,并且值为0,所以即使在声明if块之外它也是有效的

  • 给予好评.`int.TrypParse`是更好的解决方案.@Serv如果你为解析结果添加if条件或bool变量会很好.这应该证明使用int.TryParse是合理的. (2认同)

Kaj*_*nha 9

您需要对输入进行类型转换.尝试使用以下内容

int input = Convert.ToInt32(Console.ReadLine()); 
Run Code Online (Sandbox Code Playgroud)

如果值为非数字,它将抛出异常.

编辑

我知道上面的内容很快.我想改进我的答案:

String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
      switch(selectedOption) 
      {
           case 1:
                 //your code here.
                 break;
           case 2:
                //another one.
                break;
           //. and so on, default..
      }

} 
else
{
     //print error indicating non-numeric input is unsupported or something more meaningful.
}
Run Code Online (Sandbox Code Playgroud)


小智 6

int op = 0;
string in = string.Empty;
do
{
    Console.WriteLine("enter choice");
    in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Run Code Online (Sandbox Code Playgroud)

  • 这个答案应该在列表中更靠前。它是唯一能够处理错误输入并让用户重试而不抛出任何异常的方法。我只会删除“string.Empty”分配。 (2认同)

小智 5

使用这个简单的行:

int x = int.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)