본문 바로가기

장 실습: 점수를 검사해 파일에 저장하기

점수 변환과 파일 객체를 연결하고 중간에 예외가 나도 파일이 닫히는지 확인합니다.

이 장에서 만든 조각을 score_report.cpp 하나로 모읍니다.

시작 상태

예외 던지기에서 만든 score_error.cpp의 ScoreError·parseScore와 raii_file.cpp의 FileHandler를 준비합니다. cpp-study에 새 score_report.cpp를 만들고 이 조각을 모읍니다. 실행하면 같은 폴더에 good.txt와 bad.txt를 씁니다.

저장한 파일을 다음 명령으로 빌드하고 실행합니다.

g++ -std=c++20 -Wall -Wextra -g score_report.cpp -o score_report.exe
.\score_report.exe

macOS와 Linux에서는 실행 파일 이름의 .exe를 빼고 ./이름으로 실행합니다.

만들기와 확인

  • score_error.cpp의 ScoreError와 parseScore, raii_file.cpp의 FileHandler를 그대로 가져옵니다.
  • int saveScores(const std::string& name, const std::vector<std::string>& inputs)는 name 파일을 열고, 줄마다 parseScore로 검사한 뒤 그 글자를 파일에 쓰며, 점수의 합을 돌려줍니다.
  • main은 saveScores("good.txt", {"85", "70"})과 saveScores("bad.txt", {"85", "", "70"})을 차례로 부르고, 성공하면 sum: 과 합을 출력합니다.
  • ScoreError는 line 2: empty input처럼, 그 밖의 표준 예외는 error: 과 what()으로 출력합니다.

힌트: saveScores에는 try가 필요 없습니다. 예외는 지나가게 두고, 파일을 닫는 일은 FileHandler에 맡깁니다.

체크포인트

단계확인할 결과
1단계: 정상 입력85와 70을 저장하고 파일을 닫은 뒤 sum: 155가 나옵니다.
2단계: 중간 실패85 뒤에 빈 입력이 오면 둘째 줄에서 실패하며 70은 저장하지 않습니다.
3단계: 종료 순서와 파일 확인closed bad.txt가 오류 안내보다 먼저 나오고 bad.txt에는 85 한 줄이 남습니다.

다를 때 먼저 볼 곳

증상먼저 볼 곳
잘못된 점수도 파일에 기록된다handler.write보다 먼저 parseScore를 호출했는지
오류에 줄 번호가 나오지 않는다ScoreError의 catch를 std::exception의 catch보다 먼저 두었는지
오류가 첫째 줄로 표시된다각 입력을 처리하기 전에 줄 번호를 증가시켰는지

완성 파일

완성 파일 전체와 확인 결과
score_report.cpp
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

class ScoreError : public std::runtime_error {
private:
    int line_;

public:
    ScoreError(const std::string& message, int line)
        : std::runtime_error(message), line_(line) {}

    int line() const { return line_; }
};

int parseScore(const std::string& text, int line) {
    if (text.empty()) {
        throw ScoreError("empty input", line);
    }
    int value = std::stoi(text);
    if (value < 0 || value > 100) {
        throw ScoreError("score out of range", line);
    }
    return value;
}

class FileHandler {
private:
    std::ofstream file_;
    std::string name_;

public:
    explicit FileHandler(const std::string& name) : file_(name), name_(name) {
        if (!file_.is_open()) {
            throw std::runtime_error("cannot open " + name);
        }
        std::cout << "opened " << name_ << '\n';
    }

    void write(const std::string& data) {
        file_ << data << '\n';
        std::cout << "wrote " << data << '\n';
    }

    ~FileHandler() {
        std::cout << "closed " << name_ << '\n';
    }
};

int saveScores(const std::string& name, const std::vector<std::string>& inputs) {
    FileHandler handler(name);
    int sum = 0;
    int line = 0;
    for (const std::string& text : inputs) {
        ++line;
        sum += parseScore(text, line);
        handler.write(text);
    }
    return sum;
}

int main() {
    try {
        int good = saveScores("good.txt", {"85", "70"});
        std::cout << "sum: " << good << '\n';
        int bad = saveScores("bad.txt", {"85", "", "70"});
        std::cout << "sum: " << bad << '\n';
    } catch (const ScoreError& e) {
        std::cout << "line " << e.line() << ": " << e.what() << '\n';
    } catch (const std::exception& e) {
        std::cout << "error: " << e.what() << '\n';
    }
}
opened good.txt
wrote 85
wrote 70
closed good.txt
sum: 155
opened bad.txt
wrote 85
closed bad.txt
line 2: empty input

closed bad.txt가 line 2 줄보다 먼저 나오면 스택 풀기가 파일을 닫은 것입니다. bad.txt에는 85 한 줄이 남아 있으므로 saveScores는 기본 보장입니다.

더 해 보기

  • 모든 줄을 먼저 검사해 std::vector<int>에 담은 다음 파일을 열도록 바꿉니다. 빈 입력이 있으면 파일이 만들어지지 않는지 확인합니다.
  • 빈 입력 대신 범위를 벗어난 점수와 숫자가 아닌 문자열을 각각 넣습니다. parseScore에서 실패하는 위치와 선택된 catch를 따라갑니다.

이것으로 13장의 예외 처리를 마칩니다. 다음 장의 auto 키워드와 타입 추론에서는 현대 C++의 기능을 차례로 살펴보며, 먼저 컴파일러가 변수의 타입을 추론하게 하는 auto와 decltype을 다룹니다.