infinite loops from input validation.

First off let me apologize for any misconceptions I may have or mistakes I may be making. I am new to C++ and programing know-how in general, especially looping logic.

I am writing a program to display a triangular pattern using nested loops and user input for the size of the base and character used to generate the image. 99% of the program runs fine. However I am having trouble with some of my input validation.

When given an integer value for the base I can verify if it is within a certain range (0-80). However, when the user inters a "char" instead of an "int" the program enters an infinite loop.

Here is the piece of code giving me trouble. (I wont bother you with the entire chunk of code, I have commented out everything else to narrow down the problem bit)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//****************************************************************
// Pattern Displays
// program that asks user for the size of the base of a triangle
// and then generates it in a character the user chooses
// Jared Corriea, CS10 section 4322
//****************************************************************

#include <iostream>
#include <istream>
#include <string>
#include <cstdlib>      

using namespace std;

int main ()
{
    char escape;

    //do
   //{
    int base,
        height,
        fillnum,                   
        wcount = 1,
        hcount = 1;
    char symbol,
         orientation;

    cout << "Enter a value to represent the base of a triangle shape (not to exceed 80): ";
    cin >> base;


    while (base<=0 || base>80)
    {
        cout << "Please use a positive number no more than 80: ";
        cin >> base;
    }
/*

  .......

*/

    system ("PAUSE>null");

    return 0;

}

Last edited on
1
2
3
4
5
6
7
8
#include <limits>
//...
while (base<=0 || base>80) {
    std::cin.clear(); //Clearing any error flags
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //Ignoring input up to newline
    std::cout << "Please use a positive number no more than 80: ";
    std::cin >> base;
}
Thanks for the help, worked perfectly.
Topic archived. No new replies allowed.