#include <iostream>
using namespace std;
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
cout << "\nPlease enter any character and hit enter to exit: ";
/* this section clears any errors and flushes the buffer to which cin points respectively, input buffer flushing taken from cprogramming.com */
cin.clear();
while(((i = cin.get()) != '\n') && (i != EOF));
/* this time it can error out (or not) because the program is finished */
i = cin.get();
return 0;
}
Just a note on why the cprogramming.com snippit works:
cin.get() can return a value of type int, so if you enter a single character (or a string of characters), the integer value (usually the ASCII code in Windows) of the first character is returned.
Since there are still characters in the cin buffer, they must be extracted manually, which is why you use cin.get() in a while loop. The conditions for exiting the while loop check to see if the RETURN/ENTER key is pressed ('\n') or if the file pointer is at the end of the file (EOF).
BTW, if you are wondering, the program will read up to its max value or a character that will set an error bit (the max value for int is 2147483647 usually or 32767 if int is short since it is signed by default). For example, entering 1838675309abbbbbbbbbbbbb will read 1838675309, but trying 11838675309abbbbbbbbbbbbbbb will render the default value, whatever it is.
In other words, the first integer will be stored as long as its max value is not exceeded and it does not contain any error bit setting characters. Note that normally, integer types read values modulo their max value. If an error bit is set, it will not carry out that modulo operation and will instead render its default value, so 11838675309 will allow the execution of the modulo operation whereas 11838675309a will not.
/* Edit:
URL to cpprogramming.com page - http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer ... 49&id=1043284392
*/
___________________
There are (01777777777777777777772 AND 03) kinds of people, those that understand bitwise operations and those that don't. There are also that many people that understand number systems.
Last edited by rpgfan3233, June 11th, 2006 11:57 PM (Edited 1 times)