C# 콘솔 출력 및 입력 처리 방법

콘솔 기반 응용 프로그램에서는 반드시 사용자との 상호작용이 필요합니다. C#에서는 System 네임스페이스의 Console 클래스를 통해 콘솔 입출력을 처리할 수 있습니다.

콘솔 출력 방법

C#에서 콘솔에 값을 출력하는 방법은 여러 가지가 있습니다. 가장 기본적인 방법은 Console.Write() 메서드와 Console.WriteLine() 메서드를 사용하는 것입니다. Console.Write()는 줄바꿈 없이 출력하고, Console.WriteLine()은 출력 후 자동으로 줄바꿈을 수행합니다.

문자열 연결 방식

변수에 저장된 값을 콘솔에 출력하는 첫 번째 방법은 연결 연산자(+)를 사용하는 것입니다. 문자열과 변수 값을 연결하여 원하는 형태로 출력할 수 있습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EmployeeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 직원 정보 저장
            string employeeName = "김철수";
            char genderCode = 'M';
            int employeeAge = 28;
            bool maritalStatus = true;
            double monthlyPay = 3200.0;
            #endregion

            double annualIncome = monthlyPay * 12;

            Console.WriteLine("직원 이름:" + employeeName);
            Console.WriteLine("성별 코드:" + genderCode);
            Console.WriteLine("나이:" + employeeAge);
            Console.WriteLine("결혼 여부:" + maritalStatus);
            Console.WriteLine("연간 소득:" + annualIncome);

            Console.WriteLine("직원 이름:" + employeeName + "\n성별 코드:" + genderCode + "\n나이:" + employeeAge + "\n결혼 여부:" + maritalStatus + "\n연간 소득:" + annualIncome);
        }
    }
}

서식 문자열 방식

두 번째 방법은 서식 문자열을 사용하는 것입니다. 중괄호 안에 인덱스를 배치하여 값 목록의 해당 위치에 있는 변수의 값을 대입합니다. 인덱스는 0부터 시작합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EmployeeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 직원 정보 저장
            string employeeName = "김철수";
            char genderCode = 'M';
            int employeeAge = 28;
            bool maritalStatus = true;
            double monthlyPay = 3200.0;
            #endregion

            double annualIncome = monthlyPay * 12;

            Console.WriteLine("직원 이름:{0}", employeeName);
            Console.WriteLine("성별 코드:{0}", genderCode);
            Console.WriteLine("나이:{0}", employeeAge);
            Console.WriteLine("결혼 여부:{0}", maritalStatus);
            Console.WriteLine("연간 소득:{0}", annualIncome);

            Console.WriteLine("직원 이름:{0}\n성별 코드:{1}\n나이:{2}\n결혼 여부:{3}\n연간 소득:{4}",
                employeeName, genderCode, employeeAge, maritalStatus, annualIncome);
        }
    }
}

콘솔 입력 처리

사용자로부터 콘솔 입력을 받으려면 Console.ReadLine() 메서드를 사용합니다. 이 메서드는 사용자가 입력한 내용을 문자열(String) 형태로 반환합니다. 다른 데이터 타입이 필요한 경우, 적절한 Parse 메서드를 사용하여 변환해야 합니다.

타입 변환이 필요한 입력 처리

문자열을 다른 타입으로 변환하려면 각 타입에 해당하는 Parse 메서드를 사용합니다. char는 char.Parse(), int는 int.Parse(), bool은 bool.Parse(), double은 double.Parse()를 사용합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InputDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName;
            char genderValue;
            int userAge;
            bool isMarried;
            double salaryAmount, yearlySalary;

            Console.Write("직원 이름을 입력하세요: ");
            userName = Console.ReadLine();

            Console.Write("성별을 입력하세요(남성:M, 여성:F): ");
            genderValue = char.Parse(Console.ReadLine());

            Console.Write("나이를 입력하세요: ");
            userAge = int.Parse(Console.ReadLine());

            Console.Write("결혼 여부를 입력하세요(기혼:true, 미혼:false): ");
            isMarried = bool.Parse(Console.ReadLine());

            Console.Write("월급을 입력하세요: ");
            salaryAmount = double.Parse(Console.ReadLine());

            yearlySalary = salaryAmount * 12;

            Console.WriteLine("이름: " + userName + "\n성별: " + genderValue + "\n나이: " + userAge + "\n결혼 여부: " + isMarried + "\n연봉: " + yearlySalary);
        }
    }
}

코드 블록折叠 기능

Visual Studio에서#region과#endregion 지시문을 사용하면 코드를折叠 가능한 블록으로 그룹화할 수 있습니다. 이는 긴 코드를 정리하고 가독성을 높이는 데 유용합니다.

이제 다음章节에서는 응용 프로그램의 디버깅 방법에 대해 학습하겠습니다.

6월 1일 19:09에 게시됨