以下代码要求您提供姓名和姓氏。
The following code asks for your name and surname.
class Program { static void Main(string[] args) { Console.Write("Enter your name: "); string s = Console.ReadLine(); Console.WriteLine("Your name: " + s); Console.Write("Enter your surname: "); int r = Console.Read(); Console.WriteLine("Your surname: " + r); Console.ReadLine(); } }输入名称后,程序会成功显示您的输入。但是,输入姓氏后,程序立即停止。根据我的理解,Console.Read()应该返回我输入的字符串的第一个字符的int值(ASCII码?)。 为什么程序终止就在Console.Read()之后? Console.ReadLine()不应该确保程序保持打开状态吗? 我尝试过: 如果我使用字符串r = Console.ReadLine(); 那么它运作良好。
After entering the name, the program successfully displays your input. However, after entering a surname, the program stops immediately. From my understanding, Console.Read() should return an int value of the first character of the string I enter (ASCII code?). Why does the program terminate right after Console.Read()? Shouldn't Console.ReadLine() ensure the program stays open? What I have tried: if i use string r = Console.ReadLine(); then it works well.
推荐答案您的程序不会保持打开状态,因为最后一个Console.ReadLine()接受您在Console.Read()指令上按下的[Enter]。 您可能想要使用ReadKey()而不是Read()来实现所需的功能。 Your program don't stay open because the last Console.ReadLine() takes the [Enter] you pressed on Console.Read() instruction. You might want to use ReadKey() instead of Read() to achieve the desired functionality. Console.Write("Enter your name: "); string s = Console.ReadLine(); Console.WriteLine("Your name: " + s); Console.Write("Enter your surname: "); string r = Console.ReadKey(false).KeyChar.ToString(); Console.WriteLine(); Console.WriteLine("Your surname: " + r); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true);
祝你好运!
Best regards!
Console.Read ()接受输入流中的值,直到按Enter键。每次后续调用 Console.Read()都会从该输入中读取单个字符。 Console.ReadLine()从输入流中检索整行。你看到出了什么问题吗? 如果你输入XYZ并在按下Enter键> Console.Read()你有YZ< enter>在 r 设置为X的输入流中。然后 Console.ReadLine()选择剩余的YZ< enter> ;并且程序终止。这个怪癖是MSDN建议不要使用 Console.Read()赞成 Console.ReadLine()和 Console.ReadKey()代替。 使用以下代码可以很容易地证明这一点: Console.Read() accepts values into the input stream until Enter is pressed. Each subsequent call to Console.Read() reads a single character from that input. Console.ReadLine() retrieves a full line from the input stream. Do you see what's going wrong? If you type in "XYZ" and press Enter at Console.Read() you have "YZ<enter>" in the input stream with r set to X. Then Console.ReadLine() picks up the remaining "YZ<enter>" and the program terminates. This quirk is why MSDN recommends not to use Console.Read() favoring Console.ReadLine() and Console.ReadKey() instead. This is easily demonstrated with the following code: int r = Console.Read(); Console.WriteLine(Console.ReadLine()); Console.ReadKey();
输入XYZ然后回车将产生以下输出:
Typing "XYZ" then Enter will yield the following output:
XYZ YZ
更多推荐
控制台在console.read()之后终止,即使最后使用console.readline()也是如此
发布评论