【问题标题】:How to NOT print to new line c# console [duplicate]如何不打印到新行 c# 控制台 [重复]
【发布时间】:2019-09-20 06:45:42
【问题描述】:

我正在编写一个简单的程序,为此我想输出当前的 cpu 使用情况,但是使用标准的“for”或“while”循环,它每次都会在新行上打印它,让我展示一下我的内容意思是:

输出应该是:

Current cpu usage: (usage)

使用情况每秒刷新一次

现在,我想每秒刷新一次,但正如我所提到的,使用 for 或 while 循环每次都会将其打印到新行,如下所示:

Current cpu usage: (usage)
(usage)
(usage)
(usage)
(usage)

那么,我该如何刷新“使用情况”?

顺便说一句,我对c#很熟悉,所以你不必深入了解:)

谢谢

【问题讨论】:

标签: c#


【解决方案1】:

单独使用\r 字符将插入符号(“打印头”)返回到第一列。这不是写\r\n(Windows/DOS 换行序列)或\n(Unix/Linux),而是给你一个换行符。

在内部,Console.WriteLine( String x )Console.Write( String x ); Console.Write( Environment.NewLine ); 相同(在 Windows 上,Environment.NewLine"\r\n")。

试试这个:

while( true )
{
    Single cpuUsage = GetCpuUsage();
    Console.Write( "Current CPU usage: {0,5:P2}", cpuUsage );
    Console.Write( "\r" );

    await Task.Delay( 500 );
}

请注意,如果下一行比上一行短,您可能需要打印一行空白来覆盖之前的任何文本,因为之前的文本会在那里。 (但通过使用{0,5:P2},它保证该文本将始终占用 5 个字符(无论是 1% 还是 100% - 或者使用 {0,-5:P2} 代替左对齐数字)。

这种技术也适用于使用与 C#/.NET 相同的 stdin/stdout 语义的其他平台,包括 C、C++、Java 等,而 Console.SetCursorPosition API 并不通用。

【讨论】:

  • 很好,我不知道 C# 控制台响应了 \r。这与使用 SetCursorPosition 到 0 基本相同吗(如 Rufus 的回答)? 编辑:您的编辑回答了我的问题。
  • @RToyo 本质上它的工作原理相同,但SetCursorPosition 更昂贵(参见源代码here)。
【解决方案2】:

您没有显示将输出写入控制台的代码,但如果您不想编写新行,则可以使用 Console.Write(message);Console.SetCursorPosition 的组合(重置光标再次移动到行首)。

例如:

for (int i = 0; i < 100000; i ++)
{
    // Set the cursor to the beginning (0) of the current line (Console.CursorTop)
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write("count: " + i);
}

【讨论】:

    猜你喜欢
    • 2015-08-23
    • 2016-07-07
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多