c# - 如何在用户写入的同一行中写入?

标签 c#

用户输入一个数字,程序应该通过写“-”*数字中的位数来制作一个横向图表,但它在用户输入的下方写了“-”一行

当前输出: the output I get

预期输出:
the output I want to get

static void Main(string[] args)
{
    int num1, num2;
    Console.WriteLine("how many numbers will you want to enter?");
    num1 = int.Parse(Console.ReadLine());
    Console.WriteLine("Enter " + num1 + " numbers");
    for(; num1 > 0; num1--)
    {
        num2 = int.Parse(Console.ReadLine());
        Hi(num2);
    }
}
static void Hi(int num)
{
    while(num != 0)
    {
        num /= 10;
        Console.Write("-");
    }
    Console.WriteLine()
}

最佳答案

您可以在控制台中获取和设置光标位置,因此,如果您记得用户按 Enter 进行数字输入之前光标位于哪一行,则可以将光标放回该行。

此外,要打印输入长度的多个破折号,输入不必是数字(否则您会检查它)。

这样的东西应该合适:

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();
}

示例输出:

How many numbers will you want to enter? 4
Enter 4 numbers
1                   -

435                 ---
What happens long wi-----------------------

(Press enter to leave program.)

关于c# - 如何在用户写入的同一行中写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52794586/

相关文章:

c# - XNA 二维视野

c# - 如何将 nuget 包 .Net Standard 嵌入到 C# 项目中?

c# - 无法加载 DLL 'amqxcs2.dll' : The specified module could not be found. 在 Visual Studio 但不是 IIS 中工作

c# - 将启用 Ajax 的 WCF 服务公开给 C# 代码

c# - 将创建的数据传递给另一个 Controller

C# 删除 Azure Blob - 无效的 Uri

c# - 如何进行服务器端 C# SQL 验证

c# - 触发 SignalR 方法时 HttpContext.Current.Request.Cookies 出现空异常

c# - 使用 LINQ 获取包含自定义对象的列表的总和/平均值

c# - 解码 (BEncode) 种子文件