Enhancement # 3 - Trap number followed by non numeric
As you know, the Asterisk Triangle Program has one remaining flaw and it's a flaw that should be addressed.
Presently, if a user enters as input 50prime the number '50' is accepted as valid and the remaining 'prime' is ignored. If a user enters as input 50.5 the number '50' is accepted and the remaining '.5' is ignored. Ideally we need to trap this and force a true integer to be entered.
Replace this line of code
with this
You'll note that a third condition has been added to the while statement. That being cin.peek() != '\n'. What this is saying is,
"if the next character in the input buffer is not a newline character".
We know that after the execution of cin >> rows that if a true number was entered then all that is left in the input buffer is a newline ('\n') character. The peek() function merely checks for the next character in the input buffer. It doesn't remove the character from the input buffer. An entry such as '50prime' will cause the expression cin.peek() != '/n' to evaluate to true, as it detects the letter 'p', which in turn the body of the while loop is entered.
Here is the complete program code.
// 30 Apr, 2008.
#include <iostream>
using namespace std;
int main()
{
int rows, c;
cout << "Enter the number of rows (1 - 79): ";
while (!(cin >> rows) or (rows < 1 or rows > 79 or cin.peek() != '\n'))
{
cout << "Must enter an integer (1 - 79): ";
cin.clear(); // clear cin error state, if exists
while (cin.get() != '\n') // clear out non newline characters
continue;
}
for (int r = 1; r <= rows; r++)
{
for (c = 1; c <= rows - r; c++)
cout << ".";
for (; c <= rows; c++)
cout << "*";
cout << endl;
}
// exit routine
cout << "\n\n...Press 'ENTER' key to EXIT...\n";
while (cin.get() != '\n')
continue; // clear out non newline characters
cin.get(); // user to hit 'ENTER' key
return 0;
}
I think I've covered all aspects of validating against incorrect data input.
Please note that there are other ways to accept keyboard input and different methods to validate against incorrect keyboard input. Feel free to make suggestions.
- Printer-friendly version
- Login or register to post comments
- 206 reads


Recent comments
3 hours 22 min ago
1 day 3 hours ago
1 day 8 hours ago
1 day 19 hours ago
1 day 19 hours ago
3 weeks 6 days ago
3 weeks 6 days ago
4 weeks 4 hours ago
10 weeks 1 day ago
11 weeks 5 days ago