C# 기초

콘솔 입력 읽기

Console.ReadLine은 사용자가 한 줄을 입력하고 Enter를 누를 때까지 기다린 뒤 그 줄을 문자열로 돌려줍니다.

동작 원리

Console.ReadLine으로 입력을 읽고 int.TryParse로 안전하게 변환합니다.

입력이 끝나면 ReadLine이 null을 반환할 수 있어 ??로 기본값을 줍니다. int.TryParse는 숫자가 아닐 때 예외 대신 false를 반환합니다. 온라인 컴파일러에서는 프롬프트가 나타나면 답을 입력하세요.

실행 가능한 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 리뷰를 받을 수 있습니다.

모든 챌린지