Chapter 6. 분기 구문과 논리 연산자 - 프로그래밍 연습_8

SeungHee Yun·2022년 7월 24일
0

C++ 기초 플러스

목록 보기
62/115

문제 :

텍스트 파일을 열고, 파일의 끝까지 문자 단위로 읽고,

파일에 들어 있는문자들의 수를 보고하는 프로그램을 작성하라.

해답 :

#include<fstream>
#include<cstdlib>

const int SIZE = 20;

char filename[SIZE];
ifstream inFile;

cout << "읽을 파일명 입력 : ";
cin.getline(filename, SIZE);

inFile.open(filename);

if (!inFile.is_open())
{
	cout << "파일 열기 실패" << endl;
	exit(EXIT_FAILURE);
}

char ch;
int count = 0;
inFile >> ch;

while (inFile.good())
{
	++count;
	inFile >> ch;
}

if (inFile.eof())
{
    cout << "파일 끝에 도달\n";
}

if (count == 0)
{
	cout << "데이터가 없습니다.\n";
}
else
{
    cout << "문자 수 : " << count << endl;
}

inFile.close();

출처 : C++ 기초 플러스 6판 / 성안당


profile
Enthusiastic Game Developer

0개의 댓글