noob question

Hey guys,
im trying to learn C++ myself this summer and was going through some programming examples. Now, in one of the examples read, i saw this bit of code which i was kinda lost about.


double temp;
int i;
for (i = 0; i < limit; i++)
{
cout << "Enter value #" << (i+1) << ": ";
cin >> temp;
if (!cin)
{
cin.clear();
while (cin.get() != '\n')
continue;
cout <<"Bad input; process terminated.\n";
break;
}
else if (temp < 0)
{break;}
ar[i] = temp;
}
return i;

Now, the part which i am stuck on is the "if(!cin)" part. Does this mean that if the cin input is not a double type, it should proceed within the bracketed code? But, when i run the program, the exact opposite happens. I input a double value, and it still runs through the bracketed bit. But when i input a letter or something not of a double type, it says "Bad input, process terminated."
Im confused. Can anyone clarify this for me?
Thanks a lot.
No. It means that the operator >> from cin failed to store what was in the input stream into the double temp variable. Which...will fail whenever there is a non numerical character. It's an indirect way to test if 'temp' is indeed a double compared to testing 'temp' itself.
Last edited on
oh ok. Thanks.
But if i input a double value so that 'cin>>' doesnt fail, why does it execute the following code in brackets?:

if (!cin)
{
cin.clear();
while (cin.get() != '\n')
continue;
cout <<"Bad input; process terminated.\n";
break;
}

cuz as i understand it, the "if (!cin)" bit means "If the input is invalid, then execute the bracketed code." but if i enter a valid double value, why does it still execute that piece of code.
Thanks.

I know, it seems backwards...it's because that line is using a double negative to make a positive.

if(!cin) is also the same as if(!cin.fail())

where: cin.fail() returns true if the operation failed. It returns false if it passed.
It tests whether the operation of cin did not fail.

Putting the logic together it's testing if cin had not not passed.

Another alternative would be simply to change this:

1
2
cin >> temp;
	if (!cin)


to if(cin >> temp)
Dealing with double negatives can be confusing :D
Last edited on
Awesome.
Thank you so much for clearing that up for me.
Just another quick question though. Im not quite sure how long you've been programming for , but how often do you use pointers in C++?
I've been going through some exercises dealing with pointers-to-functions and it's really rough.
Thanks again for all your help.
For most tasks u can just as easily substitute using pointers for references. References accomplish (in most cases) the same thing and u'r much less likely to make mistakes with it. Learn pointers but only use them when u need to. When the time comes you'll know ;)
Topic archived. No new replies allowed.