C# 如何从控制台读取字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19860677/
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
How to read char from the console
提问by Martin Dzhonov
I have a char
array and I want to assign values from the console. Here's my code:
我有一个char
数组,我想从控制台分配值。这是我的代码:
char[] input = new char[n];
for (int i = 0; i < input.Length; i++)
{
input[i] = Console.ReadLine();
}
But I'm getting the following error:
但我收到以下错误:
Cannot implicitly convert type 'System.ConsoleKeyInfo' to 'char'
无法将类型“System.ConsoleKeyInfo”隐式转换为“char”
Is there an easy way to fix this?
有没有简单的方法来解决这个问题?
采纳答案by Kamil Budziewski
Use Console.ReadKey
and then KeyChar
to get char
, because ConsoleKeyInfo
is not assignable to char
as your error says.
使用Console.ReadKey
and then KeyChar
get char
,因为ConsoleKeyInfo
不能char
像您的错误所说的那样分配给。
input[i] = Console.ReadKey().KeyChar;
回答by Kjartan
Quick example to play around with:
使用的快速示例:
public static void DoThis(int n)
{
var input = new char[n];
for (var i = 0; i < input.Length; i++)
{
input[i] = Console.ReadKey().KeyChar;
}
Console.WriteLine(); // Linebreak
Console.WriteLine(input);
Console.ReadKey();
}
回答by ctg
Grab the first character of the String being returned by Console.ReadLine()
获取由 Console.ReadLine() 返回的字符串的第一个字符
char[] input = new char[n];
for (int i = 0; i < input.Length; i++)
{
input[i] = Console.ReadLine()[0];
}
This will throw away all user input other than the first character.
这将丢弃除第一个字符以外的所有用户输入。