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