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