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
\n
is entered. cin
ignores/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;
<< "Enter a number:" << endl;
cout >> num;
cin
// if cin.fail() is true,
// cin.ignore() will fail too
while(cin.fail()) {
// do not swtich the order
// we must clear first
.clear();
cin.ignore(1000, '\n');
cin<< "Try again!" << endl;
cout >> num;
cin }
<< "The number entered is " << num;
cout
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() {
("myFile.txt");
ifstream inputFile
int num = 0, sum = 0;
while(!inFile.eof()) {
>> num;
inFile if (inFile.fail()) {
.clear();
inFile.ignore(1000, '\n');
inFile} else {
+= num;
sum }
}
<< "Reached end of file" << endl;
cout << "The sum is " << sum << endl;
cout return 0;
}