I have made a program to make a rectangle in a text matrix. It begins asking for width and height. The variable must be greater than 2 and a whole number. The only problem is if a user enters a character instead of a number, or a decimal instead of an integer 'm stuck in an infinite loop. How do you determine whether the input is a string, a double type or integer?

``````do{
cout << "\n\tEnter the width: ";
cin >> w1;
w2 = w1;
w2 = w1;
wf = w1;
inside = w1;
inside_c = w1;
inside-=2;
inside_c = inside;
cout << "\n\tEnter the height: ";
cin >> h;
hf = h;
h-=2;
cout << "\n" << endl;
if(w1<1 || h<1){
w1 = 0;
w2, wf, inside = w1;
h = 0;
hf = h;
cout << "Please enter a number greater than 2. \n" << endl;
error26 = true;}
else{
error26 = false;}
}while(error26 == true);``````

How do you determine whether the input is a string, a double type or integer?

The state of cin will tell you if there was an error. If you ask for an integer, for example, and the operation fails, it's fairly safe to assume that the user typed the wrong thing. The conventional method is a loop that clears the stream state and discards remaining input every time this happens:

``````int x;

cout << "Please enter an integer value: ";

while (!(cin >> x)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: ";
}

cout << "The integer value was " << x << '\n';``````

The down side to this method is that if the user types something like "123foo", the "123" will be successfully read and the "foo" will be left in the stream. Depending on your needs, that could be undesirable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.