C#에서 키보드 입력 읽기
이 레슨에서는 Console.ReadLine으로 사용자 입력을 읽고 int.TryParse로 안전하게 숫자로 바꿉니다.
소개
Console.ReadLine 메서드는 사용자가 한 줄을 입력하고 Enter 키를 누를 때까지 프로그램을 멈춘 뒤, 그 줄을 문자열로 돌려줍니다. 받은 데이터는 항상 문자열이므로 계산하기 전에 숫자로 바꿔야 하고, 사용자가 잘못 입력한 경우도 처리해야 합니다.
Console.ReadLine은 더 이상 입력이 없으면 null을 돌려줄 수 있으므로, ?? 연산자로 "friend" 같은 기본값을 줍니다. int.TryParse 메서드는 문자열을 숫자로 바꾸려 시도하고, 문자열이 잘못되었으면 오류를 일으키는 대신 false를 돌려줍니다. 결과는 out int age 변수로 나옵니다. 온라인 컴파일러에서는 안내 메시지가 나타나면 답을 입력하세요.
실행 가능한 C# 예제
C#
Program.cs
using System;
class Program
{
static void Main()
{
// Console.ReadLine returns the typed line, or null when input ends.
Console.Write("What is your name? ");
string name = Console.ReadLine() ?? "friend";
// int.TryParse converts text safely instead of throwing on bad input.
Console.Write("How old are you? ");
string text = Console.ReadLine() ?? "";
if (int.TryParse(text, out int age))
{
Console.WriteLine($"Hello, {name}!");
Console.WriteLine($"In 10 years you will be {age + 10}.");
}
else
{
Console.WriteLine($"\"{text}\" is not a whole number.");
}
}
}
What is your name? Ada
How old are you? 29
Hello, Ada!
In 10 years you will be 39.디버거로 연습하기
중요한 대입이나 조건에 중단점을 두고 Debug를 눌러 다음 줄로 넘어가기 전에 지역 변수 값을 확인하세요.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- 세 수의 평균 세 개의 정수를 평균하세요. 쉬움
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. 쉬움