C# 从控制台输入获取整数

C# 从控制台输入获取整数,c#,C#,我正在尝试从用户输入中获取一个整数。我使用了以下方法 int locationX = Convert.ToInt32(Console.Read()); myObject.testFunction(locationX); 并得到一个与我的testFunction相关的意外错误。我使用了调试器,发现当我将数字2输入控制台时,locationX变为50。这里发生了什么,我如何获得locationX以匹配用户输入 使用Console.ReadLine()而不是Console.Read()- 你需要使用

我正在尝试从用户输入中获取一个整数。我使用了以下方法

int locationX = Convert.ToInt32(Console.Read());
myObject.testFunction(locationX);
并得到一个与我的testFunction相关的意外错误。我使用了调试器,发现当我将数字2输入控制台时,locationX变为50。这里发生了什么,我如何获得locationX以匹配用户输入

使用
Console.ReadLine()
而不是
Console.Read()
-

你需要使用


从控制台输入流中读取下一个字符,而不是整行,这解释了为什么会得到奇怪的结果。

在用户点击ENTER键之前,不要读取控制台输入

int locationX = Convert.ToInt32(Console.ReadLine());
myObject.testFunction(locationX);

当用户按下enter键时,您应该阅读用户输入的内容。
这是通过
Console.ReadLine
完成的。但是您在以下
转换.ToInt32
中遇到问题。 如果用户没有键入可以转换为整数的内容,代码将崩溃

从控制台读取整数的正确方法是

int intValue;
string input = Console.ReadLine();
if(Int32.TryParse(input, out intValue))
    Console.WriteLine("Correct number typed");
else
    Console.WriteLine("The input is not a valid integer");
该方法将尝试将输入字符串转换为有效整数。如果转换是可能的,那么它将设置通过参数传递的整数并返回true。否则,传递的整数将被设置为整数的默认值(零),并且该方法返回false


TryParse不会抛出昂贵的异常,如
Convert.ToInt32
或简单的
Int.Parse
方法

什么是
myObject.TestFunction
?它只是一个伪函数,变量locationX在被调用之前是50。
int intValue;
string input = Console.ReadLine();
if(Int32.TryParse(input, out intValue))
    Console.WriteLine("Correct number typed");
else
    Console.WriteLine("The input is not a valid integer");