입출력 연산이 스트림 상태 비트를 변경한다는 사실
EOF를 잘못 처리하면 무한 반복을 초래
clear()를 쓸 때는 두번 생각하자!
#include <fstream>
#include <iostream>
using namespace std;
// 다음 구분 문자까지 건너 뛰기
int main(int argc, char const *argv[])
{
ifstream fin;
int number;
fin.open("correct.txt");
while (!fin.eof())
{
fin >> number;
if (fin.fail())
{ // failbit 일때는 다시 읽지를 않는다.
fin.clear(); // failbit을 false로
fin.ignore(LLONG_MAX,
' '); // 스트림의 최대길이 LLONG_MAX까지 무시를 멈추는
// 조건 공백 문자를 만났을때.
}
else
{
cout << number << endl;
}
/* code */
}
/* code */
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
ifstream fin;
int number;
string trash;
fin.open("correct.txt");
while (true)
{
fin >> number;
if (fin.eof())
{
break;
}
if (!fin.fail())
{
cout << number << endl;
continue;
}
// failbit 일때는 stream에서 받아서 저장이 불가능하다.
fin.clear(); // 그래서 faibit false로 변환
fin >> trash; // 당시 할당
}
fin.close();
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
// only 숫자만 읽을수 있다. 예외처리 없는 프로그램
int main(int argc, char const *argv[])
{
ifstream fin;
int number;
fin.open("number.txt");
while (!fin.eof())
{
fin >> number;
cout << number << endl;
/* code */
}
return 0;
}