การใช้เมธอด Read()
เมธอด Read() ใช้เพื่อผ่านตัวอักษรตัวต่อไปจาก input steam โดยเมธอดจะส่งค่า integer ของตัวอักษรกลับมา โดยมันมีรูปแบบการใช้งานดังนี้
ตัวอย่าง
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace read__readline { class Program { static void Main(string[] args) { int variable = Console.Read(); Console.WriteLine("variable = "+ variable); Console.ReadLine(); } } }
ผลการรัน
g
variable = 103
การใช้เมธอด ReadLine()
สามารถใช้อ่าน string, integer, float, double เป็นต้น โดยเมธอดจะ return ค่ากลับมาเป็นสตริง
ตัวอย่าง
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace readline { class Program { static void Main(string[] args) { String name; int age; double height; Console.Write("You Name : "); name = Console.ReadLine(); Console.Write("You Age : "); int.TryParse(Console.ReadLine(), out age); Console.Write("You Height : "); double.TryParse(Console.ReadLine(), out height); Console.WriteLine("Name: {0}", name); Console.WriteLine("Age: {0}", age); Console.WriteLine("Height: {0}", height); Console.ReadLine(); } } }
ผลการรัน
You Name : bom
You Age : 19
You Height : 170.5
Name: bom
Age: 19
Height: 170.5