You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Console.Write与Console.WriteLine的区别及新手遇到的Console.WriteLine未触发换行问题咨询

问题解答:为什么Console.WriteLine没有触发预期的换行?

首先得明确Console.Write()Console.WriteLine()这两个方法的核心区别,这就是你遇到问题的根源:

  • Console.Write(string)只输出传入的字符串,不会在末尾自动添加换行符。执行完你的第一个语句Console.Write("This is the first line.");后,控制台的光标会停在"This is the first line."的最后一个字符(句号)后面,不会跳到下一行。
  • Console.WriteLine(string)输出传入的字符串,然后自动在末尾添加一个换行符。但要注意——这个换行是加在它输出的内容之后,而不是让它输出的内容从新的一行开始。

所以你的代码执行后,实际的输出逻辑是:

  1. 输出"This is the first line.",光标停在这句话末尾
  2. 紧接着输出"This is the second line.",然后添加换行符

最终控制台显示的内容就是:

This is the first line.This is the second line.

这显然和你预期的两行分开的效果不符。

你提到在第一个Console.Write前添加Console.WriteLine(" ")就有换行效果,其实那是因为这个语句先输出了一个空行(带换行),然后第一个Console.Write输出的内容在新的一行,第二个Console.WriteLine的内容又接在后面——但这其实是绕了弯路,并不是正确的解决方式。

正确的写法有两种:

  • 方案一:把第一个Console.Write改成Console.WriteLine,让第一行输出后自动换行:
    Console.WriteLine("This is the first line.");
    Console.WriteLine("This is the second line.");
    
  • 方案二:如果一定要用Console.Write输出第一行,就在字符串末尾手动加上换行符(\n或者Environment.NewLine,后者更适配跨平台场景):
    Console.Write("This is the first line.\n");
    Console.WriteLine("This is the second line.");
    

这样就能得到你预期的两行分开的输出效果啦。

内容的提问来源于stack exchange,提问作者cPi

火山引擎 最新活动