peek()
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>


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