Programming and Graphics

(Kiana) #1

3.4 Keyboard and monitor 65


Ensuring a successful read


If a program expects us to enter a real number and we enter instead a
character string, the execution will fail. To ensure a proper read, we use the
limitslibrary and engage the program in ado-whileloop, as illustrated in
the following code:


#include <iostream>
#include <limits>
using namespace std;

int main()
{
float a;
int flag; // for successful read

cout << "Please enter a float number:"<< endl;

do{
flag=0;
cin >> a;
if(!cin) // execute in case of a false read
{
cout << "Inappropriate input; please try again"<< endl;
flag=1;
cin.clear(); // reset the false-read flag
cin.ignore(numericlimits<streamsize>::max(),’\n’);
}
}while(flag);

cout << a << endl;

return 0;
}

The statement:


cin.ignore(numericlimits<streamsize>::max(),’\n’);

removes from the input stream the bad input.


Greatest common divisor


As an application, we discuss a code that computes the greatest common
divisor (GCD) of two integers, defined as the greatest integer that divides both.
The GCD is involved in the calculation of the structure of carbon nanotubes
parametrized by a pair of integers determining the chirality.

Free download pdf