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?

			cout << "\n\tEnter the width: ";
			cin >> w1;
			w2 = w1;
			w2 = w1;
			wf = w1;
			inside = w1;
			inside_c = w1;
			inside_c = inside;
			cout << "\n\tEnter the height: ";
			cin >> h;
			hf = h;
			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;}
				error26 = false;}
			}while(error26 == true);
5 Years
Discussion Span
Last Post by Narue

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.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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.