need assistance with do while validation..

Hi all,

Trying to determine why if user types a letter for double data type variable do-while validation gets screwy and an endless loop occurs using the following code:

#include <iostream>
using namespace std;

void main(){

double x;

do
{
cout<<"Enter value: "<<endl;
cin >> x;
cout<<"Value is: "<<x<<endl;
}while(x!=0);

}

the example works as expected when keying in numbers, but if a user enters for example the letter "w" then it just loops through the do-while block statements without the cin line re-prompting for input.

WTF - TIA!!!

Last edited on
I think it's because a character has an ASCII value and when processing a character like a number, it's ASCII value is used and it can get a bit screwy after that.
Last edited on
I don't know why your code fall in recursion but you can query that the reading is success or not:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{

	double x;

	do
	{
		cout<<"Enter value: "<<endl;
		cin >> x;
		if (!cin.good())return 1; // if the reading didn't succeed then the program running would be terminated.
		cout<<"Value is: "<<x<<endl;
	}while(x!=0);

	return 0;
}

Because when you attempt to read an int and it fails because the input stream contains non-integral data, the non-integral data is not flushed from the stream, so the second time through it reads the same non-integral data and fails again, and again, and again.

... and again and again and again and again...

Topic archived. No new replies allowed.