Lecture 7 - Sept 22, 2023
Summary
In this lecture, we discuss detecting and handling errors in the input from a file or user.
Last lecture
File I/O.
Today
Handling I/O errors.
Handling I/O errors
- Input stream if stored in a buffer.
- This buffer is only available when
\nis entered. cinignores/skips delimiters or whitespaces.- Delimiters are
,\t,\n.
Reading happens until a delimiter is seen or when something wrong happens! :::
What is cerr? It is an output stream like cout. It is unbuffered unlike cout. This means that the output appears immediately on the console/terminal.
Why return 1? Any non-zero number signals an error.
What to do when a failure with input occurs?
cin.clear() will clear the failure condition so cin.fail() and cin.eof() are back to false.
cin.ignore(int n, char ch) will discard n characters or up to character ch, whichever comes first.
Write a program that reads a number from the user. It is not a number, prompt the user again.
#include <iostream>
using namespace std;
int main() {
int num = 0;
cout << "Enter a number:" << endl;
cin >> num;
// if cin.fail() is true,
// cin.ignore() will fail too
while(cin.fail()) {
// do not swtich the order
// we must clear first
cin.clear();
cin.ignore(1000, '\n');
cout << "Try again!" << endl;
cin >> num;
}
cout << "The number entered is " << num;
return 0;
}Write a program that reads numbers from a file and prints their sum. If it reads a non-integer number, ignore it. Numbers are written on separate lines.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inputFile("myFile.txt");
int num = 0, sum = 0;
while(!inFile.eof()) {
inFile >> num;
if (inFile.fail()) {
inFile.clear();
inFile.ignore(1000, '\n');
} else {
sum += num;
}
}
cout << "Reached end of file" << endl;
cout << "The sum is " << sum << endl;
return 0;
}