图解C# Console 输出和Console相关编程复习总结

1 基本控制台输出

首先进入 SharpDevelop ,新建一个控制台工程;

SharpDevelop简介:

http://blog.csdn.net/bcbobo21cn/article/details/44200205

using System;

namespace conwrdemo
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");

			// TODO: Implement Functionality Here

			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}

结果;

2 Write()和WriteLine()的区别

Write()和WriteLine()都是System.Console提供的方法,两者主要用来将输出流由指定的输出装置(默认为屏幕)显示出来.两着间的差异在Console.WriteLine()方法是将要输出的字符串与换行控制字符一起输出,当次语句执行完毕时,光标会移到目前输出字符串的下一行.至于Console.Write()方法,光标会停在输出字符串的最后一个字符后,不会移动到下一行。

3 输出格式详解

格式项都采用如下形式:

{index[,alignment][:formatString]}

其中"index"指索引占位符;

",alignment"对齐方式,以","为标记;

":formatString"是对输出格式的限定,以":"为标记。

alignment:可选,是一个带符号的整数,指示首选的格式化字段宽度。如果“对齐”值小于格式化字符串的长度,“对齐”会被忽略,并且使用格式化字符串的长度作为字段宽度。如果“对齐”为正数,字段的格式化数据为右对齐;如果“对齐”为负数,字段的格式化数据为左对齐。如果需要填充,则使用空白。如果指定“对齐”,就需要使用逗号。

formatString:由标准或自定义格式说明符组成.

using System;

namespace conwrdemo2
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("各种数据格式的输出:");
			// Console.WriteLine 中各种数据格式的输出
            Console.WriteLine("{0, 8 :C}", 2);     // $2.00
            Console.WriteLine("{0, 8 :C3}", 2);    // $2.000
            Console.WriteLine("{0 :D3}", 2);       // 002
            Console.WriteLine("{0 :E}", 2);        // 2.000000E+000
            Console.WriteLine("{0 :G}", 2);        // 2
            Console.WriteLine("{0 :N}", 2500000.00);    // 2,500,00.00
            Console.WriteLine("{0 :x4}", 12);      // 000c
            Console.WriteLine("{0, 2 :x}", 12);    //  c
            Console.WriteLine("{0 :000.000}", 12.23);   // 012.230
            Console.WriteLine("{0 :r}", 15.62);    // 15.62
            Console.WriteLine("{0 :d}", System.DateTime.Now);    // 2012-3-27
            Console.WriteLine("{0 :D}", System.DateTime.Now);    // 2012年3月27日

            Console.WriteLine("{0 :t}", System.DateTime.Now);    // 11:43
            Console.WriteLine("{0 :T}", System.DateTime.Now);    // 11:43:34

            Console.WriteLine("{0 :f}", System.DateTime.Now);    // 2012年3月27日 11:43
            Console.WriteLine("{0 :F}", System.DateTime.Now);    // 2012年3月27日 11:43:34

            Console.WriteLine("{0 :g}", System.DateTime.Now);    // 2012-3-27 11:43
            Console.WriteLine("{0 :G}", System.DateTime.Now);    // 2012-3-27 11:43:34

            Console.WriteLine("{0 :M}", System.DateTime.Now);    // 3月27日
            Console.WriteLine("{0 :r}", System.DateTime.Now);// Tue, 27 Mar 2012 11:43:34 GMT
            Console.WriteLine("{0 :s}", System.DateTime.Now);    // 2012-03-27T11:43:34
            Console.WriteLine("{0 :u}", System.DateTime.Now);    // 2012-03-27 11:43:34Z
            Console.WriteLine("{0 :U}", System.DateTime.Now);    // 2012年3月27日 3:43:34
            Console.WriteLine("{0 :Y}", System.DateTime.Now);    // 2012年3月

            Console.WriteLine("{0 :dd}", System.DateTime.Now);   // 27
            Console.WriteLine("{0 :ddd}", System.DateTime.Now);  // 二
            Console.WriteLine("{0 :dddd}", System.DateTime.Now); // 星期二

            Console.WriteLine("{0 :f}", System.DateTime.Now);    // 2012年3月27日 11:46
            Console.WriteLine("{0 :ff}", System.DateTime.Now);   // 18
            Console.WriteLine("{0 :fff}", System.DateTime.Now);  // 187
            Console.WriteLine("{0 :ffff}", System.DateTime.Now); // 1875
            Console.WriteLine("{0 :fffff}", System.DateTime.Now); // 18750

            Console.WriteLine("{0 :gg}", System.DateTime.Now);   // 公元
            Console.WriteLine("{0 :ggg}", System.DateTime.Now);  // 公元
            Console.WriteLine("{0 :gggg}", System.DateTime.Now); // 公元
            Console.WriteLine("{0 :ggggg}", System.DateTime.Now);     // 公元
            Console.WriteLine("{0 :gggggg}", System.DateTime.Now);    // 公元

            Console.WriteLine("{0 :hh}", System.DateTime.Now);   // 11
            Console.WriteLine("{0 :HH}", System.DateTime.Now);   // 11

            Console.WriteLine("{0 :mm}", System.DateTime.Now);   // 50
            Console.WriteLine("{0 :MM}", System.DateTime.Now);   // 03

            Console.WriteLine("{0 :MMM}", System.DateTime.Now);  // 三月
            Console.WriteLine("{0 :MMMM}", System.DateTime.Now); // 三月

            Console.WriteLine("{0 :ss}", System.DateTime.Now);   // 43
            Console.WriteLine("{0 :tt}", System.DateTime.Now);   // 上午

            Console.WriteLine("{0 :yy}", System.DateTime.Now);   // 12
            Console.WriteLine("{0 :yyyy}", System.DateTime.Now); // 2012
            Console.WriteLine("{0 :zz}", System.DateTime.Now);   // +08
            Console.WriteLine("{0 :zzz}", System.DateTime.Now);  // +08:00
            Console.WriteLine("{0 :hh:mm:ss}", System.DateTime.Now);  // 11:43:34
            Console.WriteLine("{0 :dd/MM/yyyy}", System.DateTime.Now); // 27-03-2012

			// TODO: Implement Functionality Here

			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}

以下是关于输出格式的示例,该资料来自网上;

4 WriteLine()的各种重载

命名空间:   System

程序集:  mscorlib(mscorlib.dll 中)

重载列表

名称 说明

WriteLine()

将当前行终止符写入标准输出流。

WriteLine(Boolean)

将指定布尔值的文本表示形式(后跟当前行终止符)写入标准输出流。

WriteLine(Char)

Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream.

WriteLine(Char[])

将指定的 Unicode 字符数组(后跟当前行终止符)写入标准输出流。

WriteLine(Char[], Int32, Int32)

将指定的 Unicode 字符子数组(后跟当前行终止符)写入标准输出流。

WriteLine(Decimal)

将指定的 Decimal 值的文本表示形式(后跟当前行终止符)写入标准输出流。

WriteLine(Double)

将指定的双精度浮点值的文本表示形式(后跟当前行终止符)写入标准输出流。

WriteLine(Int32)

将指定的 32 位有符号整数值的文本表示(后跟当前行的结束符)写入标准输出流。

WriteLine(Int64)

将指定的 64 位有符号整数值的文本表示(后跟当前行的结束符)写入标准输出流。

WriteLine(Object)

Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.

WriteLine(Single)

将指定的单精度浮点值的文本表示形式(后跟当前行终止符)写入标准输出流。

WriteLine(String)

将指定的字符串值(后跟当前行终止符)写入标准输出流。

WriteLine(String, Object)

Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(String, Object, Object)

Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(String, Object, Object, Object)

使用指定的格式信息,将指定对象的文本表示形式(后跟当前行终止符)写入标准输出流。

WriteLine(String, Object, Object, Object, Object)

使用指定的格式信息,将指定的对象和可变长度参数列表(后跟当前行终止符)的文本表示形式写入标准输出流。

WriteLine(String, Object[])

使用指定的格式信息,将指定的对象数组(后跟当前行终止符)的文本表示形式写入标准输出流。

WriteLine(UInt32)

Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream.

WriteLine(UInt64)

Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line terminator, to the standard output stream.

5 C# Console类的具体用法

Console.Write 表示向控制台直接写入字符串,不进行换行,可继续接着前面的字符写入。

Console.WriteLine 表示向控制台写入字符串后换行。

Console.Read 表示从控制台读取字符串,不换行。

Console.ReadLine 表示从控制台读取字符串后进行换行。

Console.ReadKey 获取用户按下的下一个字符或功能键,按下的键显示在控制台窗口中。

Console.Beep 通过控制台扬声器播放提示音。

Console.Clear 清除控制台缓冲区和相应的控制台窗口的显示信息。

输出到控制台

Console.WriteLine();

Console.Write();

Console.WriteLine(输出的值);

Console.Write(输出的值);

Console.WriteLine("输出的格式字符串",变量列表);

Console.Write("输出的格式字符串",变量列表);

Console.WriteLine("鹿鼎记中{0}的妻子有{1},{2},{3}等7个",strName[0],strName[1],strName[2],strName[3]);

这种方式中包含两个参数:“格式字符串”和变量列表。“鹿鼎记中{0}的妻子有{1},{2},{3}等7个”这是格式字符串,{0}、{1}、{2}、{3}叫做占位符,代表后面依次排列的变量表,0对应变量列表的第一个变量,1对应变量列表的第2个变量,依次类推,完成输出。

从控制台输入

Console.ReadLine();

这一句代码返回一个字符串型数据,可以把它直接赋值给字符串变量,如:

string strname=Console.ReadLine();

有时需要从控制台输入数字,就用到前面介绍的内容,数据转换,如:

int num=int.Pares(Console.ReadLine());

int num=Convert.ToInt32(Console.ReadLine());

上面两句代码效果相同,可以根据自己的习惯选择任意一种。

注意:

Console.ReadLine()和Console.Read()的输入结果完全不同,不能混用。

Console.Read(),返回值为首字符的ASCII码

Console.ReadLine(),返回值为字符串

也就是说read方法只能读取第一个字符,而ReadLine能读多个字符也可以换行读取

Console.ReadKey()的作用,read是从控制台读取,key表示按下键盘,那么组合在一起的意思就是获取用户按下功能键显示在窗口中,用在前面的代码起到窗口暂停的功能,在调试状态下,只有按下任意键后窗口才会关闭。

控制台输入输出示例;

using System;
using System.Collection.Generic;
using System.Linq;
using System.Text;
namespace ConsoleTest
{
class ConsoleTest
{
static void Main(string[] args)
{
Console.WriteLine("请输入两个学生的名字");
string name1=Console.ReadLine();
string name2=Console.ReadLine();
Console.WriteLine("请输入两个学生的成绩");
int score1=int.Parse(Console.ReadLine());
int score2=int.Parse(Console.ReadLine());
Console.WriteLine("第一个学生的姓名{0},成绩{1}",name1,score1);
Console.WriteLine("第二个学生的姓名{0},成绩{1}",name2,score2);
Console.ReadKey();
}
}
}

6 调试的控制台输出

窗口程序用Debug.WriteLine

按f5调试运行

输出结果在“输出”窗格,视图-窗口-输出可以打开它。

新建一个Winform项目,在按钮单击事件输入如下图代码;

Debug.WriteLine(str1);

启动调试;单击按钮;str1的值在Output窗口输出;

7 更改控制台窗口大小、字体颜色、获得行号

using System;

namespace conwrdemo5
{
	class Program
	{
		public static void Main(string[] args)
		{
			// TODO: Implement Functionality Here
			Console.WriteLine(Console.WindowHeight);
            Console.WriteLine(Console.BufferHeight);
            Console.ReadKey();
            Console.Title = "Test";//设置窗口标题
            Console.WindowWidth = 40;
            Console.WindowHeight=20;
            Console.BufferHeight = 20;
            Console.WriteLine(Console.WindowWidth);
            Console.WriteLine(Console.WindowHeight);
            Console.WriteLine("---------------------");
            Console.WriteLine(Console.BufferWidth);
            Console.WriteLine(Console.BufferHeight);

            Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);

            Console.BackgroundColor = ConsoleColor.Blue; //设置背景色
            Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色
            Console.WriteLine("第一行白蓝.");
            Console.ResetColor(); //将控制台的前景色和背景色设为默认值
            Console.BackgroundColor = ConsoleColor.Green;
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            string str = "第三行 绿暗绿";
            Console.WriteLine(str.PadRight(Console.BufferWidth - (str.Length % Console.BufferWidth))); //设置一整行的背景色
            Console.ResetColor();

			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);

			//计算当前光标所在的行数,针对于Console.BufferHeight的值
			ShowColor();
            int m = Console.CursorTop;//查看当前行号Console.BufferHeight
            Console.ReadKey();

            Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);

		}

		//显示出console中支持的背景色及前景色

        static void ShowColor()
        {
            Type type = typeof(ConsoleColor);
            Console.ForegroundColor = ConsoleColor.White;
            foreach (string name in Enum.GetNames(type))
            {
                Console.BackgroundColor = (ConsoleColor)Enum.Parse(type, name);
                Console.WriteLine(name);
            }

            Console.BackgroundColor = ConsoleColor.Black;
            foreach (string name in Enum.GetNames(type))
            {
                Console.ForegroundColor = (ConsoleColor)Enum.Parse(type, name);
                Console.WriteLine(name);
            }

            foreach (string bc in Enum.GetNames(type))
            {
                Console.BackgroundColor = (ConsoleColor)Enum.Parse(type, bc);
                foreach (string fc in Enum.GetNames(type))
                {
                    Console.ForegroundColor = (ConsoleColor)Enum.Parse(type, fc);
                    Console.WriteLine("bc="+bc+",fc="+fc);
                }
                Console.WriteLine();
            }
        }
	}
}

Console.BufferHeight 属性:

The current height, in rows, of the buffer area.

8 Winform启动控制台并执行命令

Process pro = new Process();
			pro.StartInfo.FileName = "cmd.exe";
			//pro.StartInfo.Arguments = @"C:\Windows\System32";
			pro.StartInfo.UseShellExecute=false;
			pro.StartInfo.RedirectStandardInput=true;
			pro.StartInfo.RedirectStandardOutput=true;
			pro.StartInfo.RedirectStandardError=true;
			pro.StartInfo.CreateNoWindow=false;

			pro.Start();
			pro.StandardInput.WriteLine("ver");
			//pro.StandardInput.WriteLine("exit");
			string rs=pro.StandardOutput.ReadToEnd();

代码如下,启动了控制台,命令没有执行;下次再搞;

9 另一个设置控制台字体颜色程序

using System;

namespace conwrdemo7
{
	class Program
	{
		public static void Main(string[] args)
		{
			String nl = Environment.NewLine;
	        String[] colorNames = Enum.GetNames(typeof(ConsoleColor));

	        Console.WriteLine("{0}All the foreground colors on a constant black background.", nl);
	        Console.WriteLine("  (Black on black is not readable.){0}", nl);

	        for (int x = 0; x < colorNames.Length; x++)
	        {
	            Console.Write("{0,2}: ", x);
	            Console.BackgroundColor = ConsoleColor.Black;
	            Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorNames[x]);
	            Console.Write("This is foreground color {0}.", colorNames[x]);
	            Console.ResetColor();
	            Console.WriteLine();
	        }

	        Console.ForegroundColor = ConsoleColor.Yellow;
	        Console.Write("/x01");
	        Console.Write("/u0001");
	        Console.Write("/001");
	        Console.Write("/x10");
	        Console.Write("/u0010");
	        Console.Write("/020");

	        Console.WriteLine();
	        Console.Write("{0,-50}", "Class1.TestMethod1");
	        Console.Write("{0,-2}","/x10");
	        Console.ForegroundColor = ConsoleColor.Green;
	        Console.WriteLine("Pass");

	        Console.WriteLine();
	        Console.ForegroundColor = ConsoleColor.Yellow;
	        Console.Write("{0,-50}", "Class1.TestMethod2");
	        Console.Write("{0,-2}", "/x10");
	        Console.ForegroundColor = ConsoleColor.Red;
	        Console.WriteLine("Failed");

	        Console.ReadLine();
		}
	}
}

上述工程,一共7个小项目;

下载地址

http://pan.baidu.com/s/1o8qyWLs

文件名

conwrdemo

时间: 2024-08-05 06:57:40

图解C# Console 输出和Console相关编程复习总结的相关文章

console 输出信息美化

不久前在一些前端的网站上看到的效果,以前觉得console只是拿来做做调试,不过现在看到别人网站的console美化效果,这个还可以作为一种网站个性来显示的.. 以%c开头,后面的文字就打印的信息,后面一个参数就是样式属性:可以尝试多个样式,每碰到一个%c开头就会应用对应的样式: console.log("%c 第一个信息 %c 第二个信息 %c 第三个信息", "color:red","","color:orange;font-wei

C# Console 输出

C# Console 输出 C#控制台输出有两种方法:Write()和WriteLine(),它们都是命名空间System中Console类的方法,能够直接输出C#提供的所有基本数据类型.区别是后者输出后换行. 1.基本输出 基本数据类型的简单输出形式为: Console.Write("格式串{参数序号}",参数表); {0}和{1}分别代表后面的参数,0为第一个参数,1为第二个,以此类推. Console.Write(对象); 2.格式化输出 其形式为: Console.Write(

解决Jenkins console输出乱码

背景 Jenkins console输出乱码,如 ????????????? 1 解决办法 Jenkins Master 设置utf8 encoding Tomcat 启动脚本 export JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF-8" Jenkins 系统管理 环境变量 Key: LANG, Value zh_CN.UTF-8 Jenkins Slave 启动脚本 nohup java "-Dfile.encoding=UTF-8 -j

java程序运行中如果出现异常未被处理,将会被抛到java虚拟机进行处理,程序中断运行后被挂起,在页面输出错误信息(不会输出到console)

下面的代码中,因为我是使用 for (Iterator<Element> i = el.elements().iterator(); i.hasNext(); ) 迭代器遍历根节点的所有子节点的flag,但是因为linux基线有 <initcmd> 节点,导致flag为空, 在传入service中进行数据库操作时抛出异常未被处理导致程序被挂起,错误信息不输出到console,直接打印到了页面. 解决方法就是try catch处理掉异常并返回false即可 public boolea

console.log()与console.dir()

console.log()可以取代alert()或document.write(),在网页脚本中使用console.log()时,会在浏览器控制台打印出信息. console.dir()可以显示一个对象所有的属性和方法. 代码格式: 之前想打印输出,ul的相关属性 控制台输出结果: 现在可以利用console.dir直接获取相关属性 控制台输出打印结果 . 原文地址:https://www.cnblogs.com/jianxian/p/10667125.html

C#里面Console.Write()和Console.WriteLine()有什么区别?

Console.Write()和Console.WriteLine()都是System.Console提供的方法,两着主要用来将输出流由指定的输出装置(默认为屏幕)显示出来.两着间的差异在Console.WriteLine()方法是将要输出的字符串与换行控制字符一起输出,当次语句执行完毕时,光标会移到目前输出字符串的下一行.至于Console.Write()方法,光标会停在输出字符串的最后一个字符后,不会移动到下一行.比如说Console.WriteLine("a");Console.

[转]console.time和console.timeEnd用法

console.time和console.timeEnd这两个方法可以用来让WEB开发人员测量一个javascript脚本程序执行消耗的时间.随着WEB应用越来越重要,JavaScript的执行性能也日益受到重视,WEB开发人员知道一些性能测试机器是必须的.今天要介绍的console.time和console.timeEnd就是其中之一. console.time方法是开始计算时间,console.timeEnd是停止计时,输出脚本执行的时间. // 启动计时器 console.time('te

cpp文件调用CUDA .cu文件实现显卡加速相关编程

本篇文章谈的是cpp文件如何调用CUDA的.cu文件实现显卡加速的相关编程.当然,这是在默认已经配置好CUDA的情况下进行的,如果对于如何配置CUDA还有疑问可以看之前写的这一篇文章.另外,现在CUDA已经放出了支持VS2013的6.5版本,所以还是建议用最新的,毕竟VS2013好用太多,配置起来也没什么区别.关于那篇配置文章,并没有解决CUDA相关函数偶有错误提示的问题,虽然对于编译没有影响,但是对于有强迫症的人来说还是比较纠结的,本人研究过后会更新,望周知. 关于如何通过cpp文件调用CUD

《转载》 cpp文件调用CUDA .cu文件实现显卡加速相关编程

转自:   http://m.blog.csdn.net/blog/oHanTanYanYing/39855829 本篇文章谈的是cpp文件如何调用CUDA的.cu文件实现显卡加速的相关编程.当然,这是在默认已经配置好CUDA的情况下进行的,如果对于如何配置CUDA还有疑问可以看之前写的这一篇文章.另外,现在CUDA已经放出了支持VS2013的6.5版本,所以还是建议用最新的,毕竟VS2013好用太多,配置起来也没什么区别.关于那篇配置文章,并没有解决CUDA相关函数偶有错误提示的问题,虽然对于