#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
char ch;
char idnum[5];
idnum[4] = 0;
ofstream fout("test.dat");
if(!fout) {
cout << "Cannot open test.dat for output.\n";
return 1;
}
fout << "A #pending\n, B, #8875\n";
fout.close();
if(!fout.good()) {
cout << "Error creating data file.";
return 1;
}
ifstream fin("test.dat");
if(!fin) {
cout << "Cannot open test.dat for input.\n";
return 1;
}
fin.exceptions(ios::badbit | ios::failbit);
try {
do {
fin.ignore(40, '#');
if(fin.eof()) {
fin.clear(); // clear eofbit
break;
}
ch = fin.peek();
if(isdigit(ch)) {
fin.read((char *)idnum, 4);
cout << "ID #: " << idnum << endl;
} else {
cout << "ID not available: ";
ch = fin.get();
while(isalpha(ch)) {
cout << ch;
ch = fin.get();
};
fin.unget();
cout << endl;
}
} while(fin.good());
} catch(ios_base::failure exc) {
cout << "Error reading data file.\n";
}
try {
fin.close();
} catch (ios_base::failure exc) {
cout << "Error closing data file.";
return 1;
}
return 0;
}
|