Console Input/output
Console calss:System.Console
1.Input
1.1 Read()
- 读取一个字符
- 默认返回值:-1
int i = Console.Read();
char ch = (char) i; // Cast the int to char
// Gets the code of the entered symbol
Console.WriteLine("The code of '{0}' is {1}.", ch, i);
1.2 ReadKey()
- 读取一个关键字
- 返回类型:ConsoleKeyInfo
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Character entered: " + key.KeyChar);
Console.WriteLine("Special keys: " + key.Modifiers);
1.3 ReadLine()
- 读取一整行字符
- 如果输入为空(eg:Ctrl+Z…),返回null
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
1.4 读取数字类型
通过console 数字不能准确读入
- 准确读取数字的步骤:
- 读一个字符串数值
- 将字符串数值转化为数字(使用prase or Convert)
1.4.1 Prase
int.Parse(string)–string->int long.Parse(string)–string->long float.Parse(string)–string->float
eg:
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}", a, b, a+b);
Console.WriteLine("{0} * {1} = {2}", a, b, a*b);
float f = float.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);
}
1.4.2 Convert
Convert.ToInt32(string[,base])–string->int Convert.ToSingle(string)–string->float Convert.ToInt64(string)–string->long
eg:
string s = "123";
int i = Convert.ToInt32(s); // i = 123
long l = Convert.ToInt64(s); // l = 123L
string invalid = "xxx1845";
int value = Convert.ToInt32(invalid);
// FormatException
1.4.3 解析时的错误处理
- 两种方法:
- try-catch
- TryPrase()
eg:
string str = Console.ReadLine();
int number;
if (int.TryParse(str, out number))
{
Console.WriteLine("Valid number: {0}", number);
}
else
{
Console.WriteLine("Invalid number: {0}", str);
}
2.Output
2.1 Write()
- 打印指定数据到控制台
double a = 15.5;
int b = 14;
...
Console.Write("{0} + {1} = {2}", a, b, a + b);
// 15.5 + 14 = 29.5
2.2WriteLine()
- 打印指定数据到控制台并移动到下一行
string name = "Marry";
int year = 1987;
...
Console.WriteLine("{0} was born in {1}.", name, year);
// Marry was born in 1987.
// Interpolated Strings –from C#6 (VS 2015)
Console.WriteLine("{name} was born in {year}.");
//下一行打印将从新行开始
2.2.1 Formatting Strings:
{index[,alignment][:formatString]}
eg1:
static void Main()
{
double pi = 1.234;
Console.WriteLine("{0:0.000000}", pi);
// 1.234000
}
eg2-打印菜单:
double colaPrice = 1.20;
string cola = "Coca Cola";
double fantaPrice = 1.20;
string fanta = "Fanta Dizzy";
double zagorkaPrice = 1.50;
string zagorka = "Zagorka";
Console.WriteLine("Menu:");
Console.WriteLine("1. {0} –{1}", cola, colaPrice);
Console.WriteLine("2. {0} –{1}", fanta, fantaPrice);
Console.WriteLine("3. {0} –{1}", zagorka, zagorkaPrice);
Console.WriteLine("Have a nice day!");
2.2.2 打印特殊字符
- 步骤:
- 更改控制台属性以启用 Unicode 友好字体
- 为控制台启用 Unicode通过调整其输出编码(首选UTF8)
eg:
using System.Text;
…
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Това е кирилица: ☺");