หากต้องการอ่านอินพุตเป็นจำนวนเต็มใน C# ให้ใช้เมธอด Convert.ToInt32()
res = Convert.ToInt32(val);
มาดูกันว่า −
Convert.ToInt32 จะแปลงการแสดงสตริงของตัวเลขที่ระบุเป็นจำนวนเต็มลงนามแบบ 32 บิตที่เทียบเท่า
ประการแรก อ่านคอนโซลอินพุต -
string val; val = Console.ReadLine();
หลังจากอ่านแล้ว ให้แปลงเป็นจำนวนเต็ม
int res; res = Convert.ToInt32(val);
เรามาดูตัวอย่างกัน −
ตัวอย่าง
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string val;
int res;
Console.WriteLine("Input from user: ");
val = Console.ReadLine();
// convert to integer
res = Convert.ToInt32(val);
// display the line
Console.WriteLine("Input = {0}", res);
}
} ผลลัพธ์
Input from user: Input = 0
ต่อไปนี้เป็นผลลัพธ์ ผู้ใช้ป้อนอินพุต
Input from user: 2 Input = 2