SOURCE FILE: ex0810.cpp
//
// Example 8.10. Program to read a nonnegative integer one character
// at a time and to print the integer or an error message
//
#include <iostream.h>
#include <ctype.h>
#include "boolean.h"
int main(void)
{
int GetNonnegative(void);
int nonneg_int; // nonnegative integer user enters
cout << "Enter a nonnegative integer and press return.\n";
cout << "Do not use a sign and only type digits.\n";
cout << "Your nonnegative integer: ";
nonneg_int = GetNonnegative();
if (nonneg_int < 0)
cout << "Sorry, input line is invalid.\n";
else
cout << "Your nonnegative integer is " << nonneg_int << ".\n";
return 0;
}
//
// Function to read characters, verifying that they are digits,
// and to accumulate the digits into a nonnegative integer.
// The function does not check for integer overflow.
// Pre: none
// Post: A nonnegative integer was returned; or in the case
// of an error, -1 was returned.
//
int GetNonnegative(void)
{
const int NEWLINE = '\n';
int nonneg_int; // nonnegative integer user enters
boolean_t InputOK; // boolean value for continuing loop
char ch; // character input from user
cin >> ch; // skip over white space at beginning of line
// Verify each character input is a digit and accumulate
nonneg_int = 0;
InputOK = TRUE;
while (!isspace(ch) && InputOK)
{
if (isdigit(ch)) // in number, accumulate and cont.
{
nonneg_int = nonneg_int * 10 + ch - '0';
cin.get(ch);
}
else // Error: character not a digit
{
cout << ch << " is not a digit.\n";
InputOK = FALSE;
}
}
// If number valid, make sure nothing else on line.
while (ch != NEWLINE && InputOK)
{
if (isspace(ch))
cin.get(ch);
else // Error: additional values on line
{
cout << "Have only one integer per line.\n";
InputOK = FALSE;
}
}
// Error detected. Last processed character not NEWLINE
if (!InputOK)
{
nonneg_int = -1;
cin.ignore(256, '\n');
}
return nonneg_int;
}