C# 您如何等待同一 Console.WriteLine() 行上的输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/316582/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:55:31  来源:igfitidea点击:

How do you wait for input on the same Console.WriteLine() line?

c#

提问by

I want to pose a question such as:

我想提出一个问题,例如:

What is your name? Joe

你叫什么名字?乔

How would I accomplish this using Console.WriteLineto also wait for the response on that same line instead of it being broken into:

我将如何使用Console.WriteLine来等待同一行上的响应而不是将其分解为:

What is your name?

Joe

你叫什么名字?

采纳答案by Matt Hamilton

Use Console.Write instead, so there's no newline written:

使用 Console.Write 代替,所以没有写换行符:

Console.Write("What is your name? ");
var name = Console.ReadLine();

回答by Jon Skeet

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLinedoes this automatically, but I'd seen oddities when just using Console.Writeand then waiting. So Matt's code becomes:

正如马特所说,使用Console.Write. 我还建议明确地刷新输出,但是 - 我相信WriteLine这是自动执行的,但是我在使用Console.Write然后等待时看到了奇怪的情况。所以马特的代码变成了:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();