Have you read the documentation?
Read
方法在鍵入輸入字符時會阻止它的返回; 當您按Enter鍵時,它會終止。按Enter鍵將 平臺相關的行終止序列添加到您的輸入中(例如, Windows會附加回車換行符序列)。 隨後調用 Read方法一次檢索您輸入的一個字符。在檢索到最後的 字符後,Read再次阻止其返回,並重復循環。
注意,你不會得到-1除非你執行 下列操作之一屬性值:同時按下Control修改鍵和Z控制檯 鍵(按Ctrl + Z),這標誌着最終OF-文件條件;按一個等效鍵 ,表示文件結束條件,例如Windows中的F6功能鍵; 或將輸入流重定向到具有實際 文件結束符的源(如文本文件)。
的ReadLine
方法或KeyAvailable
屬性和ReadKey
方法是 優選使用Read方法。
如果我執行此代碼:
Console.Write("? ") ;
int input = Console.Read() ;
Console.WriteLine("You entered {0}.", input) ;
Console.WriteLine("{0} is the decimal code point for the character whose glyph is '{1}.'" , input , (char)input) ;
而且,如果是我,在?
提示符下,輸入隨後return
鍵的字符123
:
? 123<return>
我會看到此輸出:
You entered 49.
49 is the decimal code point for the character whose glyph is '1'.
[注意在Windows中,可以產生在按住<ALT>
鍵,鍵入「0049 and releasing the
`鍵的命令提示符「1」]
假設目的是爲用戶指定你需要的代碼看起來像這樣:
static void Main()
{
int n = ReadIntegerFromConsole("How many values do you want to enter?") ;
int[] values = new int[n] ;
for (int i = 0 ; i < values.Length ; ++i)
{
string prompt = string.Format("{0}/{1}?" , i , n) ;
values[i] = ReadIntegerFromConsole(prompt) ;
}
Console.WriteLine("You entered: {0}" , string.Join(", ",values)) ;
return ;
}
static int ReadIntegerFromConsole(string prompt)
{
int value ;
bool isValid ;
do
{
Console.Write(prompt) ;
Console.Write(' ');
string text = Console.ReadLine() ;
isValid = int.TryParse(text, out value) ;
prompt = "That's not an integer. Try again:" ;
} while (!isValid) ;
return value ;
}
使用'Console.ReadLine()'而不是'Console.Read()'來代替輸入值。 。 – MarcinJuraszek
@MarcinJuraszek你應該在猜測之前運行代碼... – Bogdan
@Bogdan是什麼讓你覺得我沒有? – MarcinJuraszek