Quote:Original post by Austin0vQuote:Original post by SiCrane
Well, the way you have it now you don't do any error detection and you're making an assumption discarding 256 characters will get you to the next line. For example, try feeding your program "Moo" as the number and watch what happens. Or 5 a space and then a few hundred 5's after that before you hit enter.
Just curious, what's the proper way to use the ignore function with proper error detection?
Don't. Instead, use the following "buffering" strategy.
Read each line of input into a string. That way you will never have to 'ignore' anything, since you always read everything that's currently available on std::cin.
Then, use the std::stringstream object to attempt to pull data out of the string (your "buffer"). If it doesn't work (because the input data was invalid), you can simply try again, and you don't have to reset anything. The next time through the loop, you get a brand new stringstream object, with the next line of user input.
You can simplify things for yourself a little bit by making a templated function to get the line, read in from it into a value, and return whether or not it was successful.
// input and output practice#include <iostream>#include <string>#include <sstream> // where std::stringstream lives.using namespace std;template <typename T>bool getValue(istream& is, T& result) { string line; getline(is, line); return std::stringstream(line) >> result;}int main() { int i; string name; do { cout << "Please enter a number: "; } while (!getValue(cin, i)); cout << "You entered the number " << i << endl; // minor English lesson here :) cout << "If you multiply that by 2 you get " << i*2 << endl; cout << "What is your name? "; getline(cin, name); // the input data is always in string format ;) cout << "\nhello " << name << " you're awesome!";}
Edit: Er, of course. Behold as I completely fail at being a ninja and editing it in. =)
[Edited by - Zahlman on August 19, 2008 9:49:59 PM]