091
[C#] TQC+ 문제 CS_505: 본문
728x90
🔍C#: CS_505.
주어진 파일인 read.txt에서 13줄 중에 사용자가 입력한 조건에 부합하는 줄의 이름과 총합 값을 출력하시오.
1. 문제 정답
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace CS_505{
class CS_505{
static string filePath = "read.txt";
static void Main(){
try{
List<string> list = new List<string>();
string[] input = Console.ReadLine().Split(' ');
int value = int.Parse(input[1]);
if(File.Exists(filePath)){
using(StreamReader reader = new StreamReader(filePath)){
string line;
while((line = reader.ReadLine()) != null){
bool result = false;
string[] words = line.Split(',');
int total = int.Parse(words[3]) + int.Parse(words[4]) + int.Parse(words[5]);
switch(input[0]){
case ">":
result = total > value;
break;
case "<":
result = total < value;
break;
case "=":
result = total == value;
break;
case ">=":
result = total >= value;
break;
case "<=":
result = total <= value;
break;
default:
throw new Exception();
break;
}
if(result) list.Add($"{words[0]} {total}");
}
Console.WriteLine(list.Count);
foreach(string l in list){
Console.WriteLine(l);
}
}
}
} catch {
Console.Write("error");
}
}
}
}
2. 정리
- List 컬렉션을 이용하기 위해서는 using System.Collections.Generic을 작성해줘야합니다. 그리고 list를 사용할 때 개수를 셀 때는 Count를 값을 추가할 때는 Add()를 사용해줍니다.
- 파일을 읽을 때 reader.ReadLine()을 만날 때마다 다음줄로 넘어가니 받은 값을 나눌 때는 저장한 변수값으로 사용해줘야합니다.
- 입력받은 문자열인 >와 같은 기호는 자체적으로 이용할 수 없으므로 bool로 결과값을 비교하여 저장해두는 것이 좋습니다.
728x90
'Programming Language > C#' 카테고리의 다른 글
[C#] TQC+ 문제 CS_507: (0) | 2025.05.26 |
---|---|
[C#] TQC+ 문제 CS_506: (0) | 2025.05.26 |
[C#] TQC+ 문제 CS_504: (0) | 2025.05.26 |
[C#] TQC+ 문제 CS_503: (0) | 2025.05.26 |
[C#] TQC+ 문제 CS_502 : (0) | 2025.05.26 |