C# Console.Read() 和 Console.ReadLine() 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12308098/
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
Console.Read() and Console.ReadLine() problems
提问by Mike Cornell
I have been trying to use Console.Read() and Console.ReadLine() in C# but have been getting weird results. for example this code
我一直在尝试在 C# 中使用 Console.Read() 和 Console.ReadLine() 但得到了奇怪的结果。例如这个代码
Console.WriteLine("How many students would you like to enter?");
int amount = Console.Read();
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
has been giving me that amount = 49 when I input 1 for the number of students, and Im not even getting a chance to input a student name.
当我为学生人数输入 1 时,一直给我这个数量 = 49,我什至没有机会输入学生姓名。
回答by Tigran
This because you read a char.
Use appropriate methods like ReadInt32()that takes care of a correct conversion from the read symbol to the type you wish.
这是因为你读了一个字符。使用适当的方法ReadInt32()来处理从读取符号到您想要的类型的正确转换。
The reason why you get 49is because it's a char code of the '1' symbol, and notit's integer representation.
你得到的原因49是因为它是“1”符号的字符代码,而不是整数表示。
char code
0 : 48
1 : 49
2: 50
...
9: 57
for example: ReadInt32()can look like this:
例如:ReadInt32()可以是这样的:
public static int ReadInt32(string value){
int val = -1;
if(!int.TryParse(value, out val))
return -1;
return val;
}
and use this like:
并像这样使用:
int val = ReadInt32(Console.ReadLine());
It Would be really nice to have a possibility to create an extension method, but unfortunately it's not possible to create extension method on static type and Consoleis a statictype.
有可能创建一个真的很好extension method,但不幸的是,不可能在静态类型上创建扩展方法,而Console是一种static类型。
回答by w.brian
Console.Read()is returning the char code of the character that you enter. You need to use Convert.ToChar(amount);to get the character as a string, and then you will need to do int.Parse()to get the value you're looking for.
Console.Read()正在返回您输入的字符的字符代码。您需要使用Convert.ToChar(amount);将字符作为字符串获取,然后您需要执行int.Parse()获取您要查找的值。
回答by Steve
Try to change your code in this way
尝试以这种方式更改您的代码
int amount;
while(true)
{
Console.WriteLine("How many students would you like to enter?");
string number = Console.ReadLine();
if(Int32.TryParse(number, out amount))
break;
}
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
Instead to use Readuse ReadLineand then check if the user input is really an integer number using Int32.TryParse. If the user doesn't input a valid number repeat the question.
Using Console.Readwill limit your input to a single char that need to be converted and checked to be a valid number.
而不是使用ReaduseReadLine然后检查用户输入是否真的是一个整数,使用Int32.TryParse. 如果用户未输入有效数字,则重复该问题。
使用Console.Read会将您的输入限制为需要转换并检查为有效数字的单个字符。
Of course this is a brutal example without any error checking or any kind of safe abort from the loops.
当然,这是一个残酷的例子,没有任何错误检查或任何类型的循环安全中止。
回答by Rune FS
you get a character charfrom read not an int. you will need to make it a string first and parse that as a string. THe implementation could look like the below
你char从 read得到一个字符而不是 int。您需要先将其设为字符串并将其解析为字符串。实现可能如下所示
Console.WriteLine("How many students would you like to enter?");
var read = Console.ReadLine();
int amount;
if(int.TryParse(read,out amount)) {
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
}
I've changed it to use readline because readline returns a string an doesn't arbitrarily limits the number of students to 9 (the max number with one digit)
我已将其更改为使用 readline,因为 readline 返回一个字符串并且不会任意将学生人数限制为 9(一位数的最大人数)
回答by rumburak
Instead of:
代替:
int amount = Console.Read();
try:
尝试:
int amount = 0;
int.TryParse(Console.ReadLine(), out amount);
Its because You read just character code, so for example typing 11 You will still get 49. You need to read string value and the parse it to int value. With code above in case of bad input You will get 0.
这是因为您只读取字符代码,因此例如键入 11 您仍然会得到 49。您需要读取字符串值并将其解析为 int 值。使用上面的代码,以防输入错误,您将得到 0。
回答by Servy
Console.Readreturns the asci value of the key character that was pressed.
Console.Read返回按下的键字符的 asci 值。
If you use Console.ReadKey().KeyCharyou'll get a charthat represents the actual character that was pressed.
如果您使用,Console.ReadKey().KeyChar您将获得char代表按下的实际字符的 。
You can then turn that character to a one character string by using .ToString().
然后,您可以使用 将该字符转换为一个字符串.ToString()。
Now that you have a string you can use int.Parseor int.TryParseto turn a string containing entirely numeric characters into an integer.
现在您有了一个字符串,您可以使用int.Parse或int.TryParse将包含完全数字字符的字符串转换为整数。
So putting it all together:
所以把它们放在一起:
int value;
if (int.TryParse(Console.ReadKey().KeyChar.ToString(), out value))
{
//use `value` here
}
else
{
//they entered a non-numeric key
}
回答by gerald
Console.WriteLine("How many students would you like to enter?");
string amount = Console.ReadLine();
int amt = Convert.ToInt32(amount);
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i = 0; i < amt; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
//thats it
回答by Kartikey Kushwaha
Try this:
尝试这个:
int amount = ReadInt32();
or if it doesn't work try this:
或者如果它不起作用试试这个:
int amount = Console.ReadInt32();
or this:
或这个:
int amount = Convert.ToInt32(Console.Readline());
In this, it will read string then it will convert it into Int32 value.
在这里,它将读取字符串,然后将其转换为 Int32 值。
You can also go here: http://www.java2s.com/Tutorials/CSharp/System.IO/BinaryReader/C_BinaryReader_ReadInt32.htm
你也可以去这里:http: //www.java2s.com/Tutorials/CSharp/System.IO/BinaryReader/C_BinaryReader_ReadInt32.htm
If nothing works, please let me know.
如果没有任何效果,请告诉我。
回答by Bamidele Adetayo
For someone who might still need this:
对于可能仍然需要这个的人:
static void Main(string[] args)
{
Console.WriteLine("How many students would you like to enter?");
var amount = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i = 0; i < amt; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
}
回答by RBT
TL;DR;Enterkey in Windows isn't a single character. This fact is at the root of many issues related to Console.Read()method.
TL; 博士; EnterWindows 中的键不是单个字符。这个事实是许多与Console.Read()方法相关的问题的根源。
Complete Details:
If you run below piece of code on your computer then you can solve lot of mysteries behind Console.Read():
完整的细节:如果你在你的电脑上运行下面的一段代码,那么你可以解决很多背后的谜团Console.Read():
static void Main(string[] args)
{
var c = Console.Read();
Console.WriteLine(c);
c = Console.Read();
Console.WriteLine(c);
}
While running the program, hit the Enterkey just once on your keyboard and check the output on console. Below is how it looks:
运行程序时,Enter只需按一下键盘上的键并检查控制台上的输出。下面是它的外观:
Interestingly you pressed Enterkey just once but it was able to cater to two Read()calls in my code snippet. Enterkey in windows emits two characters for a new line character namely carriage return (\r- ASCII code 13) and line feed (\n- ASCII code 10). You can read about it more here in this post - Does Windows carriage return \r\n consist of two characters or one character?
有趣的是,您只按Enter了一次键,但它能够满足Read()我的代码片段中的两次调用。EnterWindows 中的键为换行符发出两个字符,即回车(\r- ASCII 代码 13)和换行(\n- ASCII 代码 10)。您可以在这篇文章中阅读更多相关信息 - Windows 回车 \r\n 是由两个字符还是一个字符组成?


