2

ReadLine() 方法不接受字符串,程序在不读取字符串的情况下执行,如输出所示。

using System;

namespace ReadReadLineMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //using read method
            Console.WriteLine("Write a character: ");
            char a=(char)Console.Read();
            Console.WriteLine(a);
            //using readline method
            Console.WriteLine("Enter a line: ");
            string s=Console.ReadLine();
            Console.WriteLine(s);
        }
    }
}

输出

4

1 回答 1

6

您的问题是由 Read 调用引起的,该调用仅从标准输入流中读取一个字符,但是当您键入字母“a”后跟 Enter 键时,您将在输入中插入 3 个字符:字母“a”,回车和换行。最后两个字符不会被 Read 从输入流中删除,并且在您调用 ReadLine 时仍然存在。当然,这会导致 ReadLine 立即退出而没有任何返回。

您可以将对 Read 的调用更改为另一个 ReadLine 以删除由 enter 键插入的 CR/LF,如果您想要单个字符,您可以从返回的字符串中提取它

Console.WriteLine("Write a character: ");
string input = Console.ReadLine();
// Decide what default you want
char a = input.Length > 0 ? input[0] : ' ';
Console.WriteLine(a);
于 2017-12-23T11:41:40.610 回答