C# 我如何写用户写的同一行?
用户输入一个数字,程序应通过在数字中写入“-”*数字量来制作一个横向图形,但它在用户输入下写入“-”a行 电流输出: 预期输出:C# 我如何写用户写的同一行?,c#,C#,用户输入一个数字,程序应通过在数字中写入“-”*数字量来制作一个横向图形,但它在用户输入下写入“-”a行 电流输出: 预期输出: 使用如下方法: public string getKeyBuffer() { string buffer = ""; do { var charIn = Console.ReadKey(true); if (charIn.Key == ConsoleKey.Enter) break; buff
使用如下方法:
public string getKeyBuffer()
{
string buffer = "";
do
{
var charIn = Console.ReadKey(true);
if (charIn.Key == ConsoleKey.Enter) break;
buffer += charIn.KeyChar;
Console.Write(charIn.KeyChar);
} while (true);
return buffer;
}
这将回显每个按下的键,然后在用户按下
回车
键后返回所有按下的键,而不回显回车
键。您可以在控制台中获取并设置光标位置,因此如果您记得在用户按下回车键输入数字之前光标所在的行,您可以将光标放回该行
此外,要打印输入长度的多个破折号,输入不必是数字(否则您会对此进行检查)
像这样的东西应该是合适的:
static void Main(string[] args)
{
Console.Write("How many numbers will you want to enter? ");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter " + num1 + " numbers");
for (; num1 > 0; num1--)
{
int currentLine = Console.CursorTop;
string num2 = Console.ReadLine();
Console.SetCursorPosition(20, currentLine);
Console.WriteLine(new string('-', num2.Length));
}
Console.WriteLine("\r\n(Press enter to leave program.)");
Console.ReadLine();
}
样本输出:
您要输入多少个数字?4.
输入4个数字
1 -
435 ---
长时间后会发生什么-----------------------
(按enter键退出程序。)
最好的解决方案是向控制台以外的其他地方写入,在控制台中,您可以绝对控制显示内容和位置
另一种解决方案是在代码中格式化一个字符串,然后清除控制台并每次编写整个内容
另一个解决方案是跟踪您所在的位置,并使用console.SetCursorPosition
移动控制台光标。然而,考虑到存在更好的输出替代方案,这很少是一个令人满意的解决方案
您可以使用
Console.CursorTop-->将光标上移一行代码>,避免了跟踪您所在线路的必要性 如果用户已按enter键,则您已进入下一行。据我所知,没有办法做到这一点,你可以使用Console.ReadKey(true)
在不显示的情况下读取字符;检查enter键,如果为false,则返回字符,否则输出破折号。但不允许编辑未提交的输入。这是一项要求吗?1)对于控制台程序来说可能有点困难。2) 首先需要获取当前控制台窗口中的内容。该程序可能已在其他内容已存在的情况下从命令行调用。4) 这不考虑水平位置。
static void Main(string[] args)
{
Console.Write("How many numbers will you want to enter? ");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter " + num1 + " numbers");
for (; num1 > 0; num1--)
{
int currentLine = Console.CursorTop;
string num2 = Console.ReadLine();
Console.SetCursorPosition(20, currentLine);
Console.WriteLine(new string('-', num2.Length));
}
Console.WriteLine("\r\n(Press enter to leave program.)");
Console.ReadLine();
}