Programming Language/C#

[C#] TQC+ 문제 CS_501 :

공구일 2025. 5. 26. 12:51
728x90

🔍C#: CS_501 .

주어진 파일인 read.txt에서 10줄 중 사용자가 입력한 값을 출력하시오. 이외의 문자나 출력할 수 없는 줄의 숫자를 입력한 경우 error를 출력하시오.

 

1. 문제 정답

using System;
using System.IO;

namespace CS_501{
    class CS_501{
        static string filePath = "read.txt";
        static void Main(){
            try{
                int input = int.Parse(Console.ReadLine());
                if(input >= 11 || input <= 0){
                    throw new Exception();
                }
                if(File.Exists("read.txt")){
                    using(StreamReader reader = new StreamReader("read.txt")){
                        string line;
                        int count = 1;
                        while((line = reader.ReadLine()) != null){
                            if(input == count){
                                Console.Write($"{input}:{line}");
                                return;
                            }
                            count++;
                        }
                    }
                }
            } catch {
                Console.Write("error");
            }
        }
    }
}

 

2. 정리

- 파일을 읽을 때는 StreamReader 인스턴스를 만들어 사용합니다. 파일이 있는지 우선적으로 확인하는 File.Exists()를 조건으로 넣어주고 그 다음 using을 이용하여 인스턴스를 만들어주는 때 이때 using은 리소스를 자동으로 해제해주는 역할입니다. StreamReader를 사용할 때는 무조건 Close()나 Dispose()를 직접 호출해줘야하지만 using을 통해 자동 관리할 수 있습니다.

728x90