|
Hello,
I am writing a script that needs to get a numeric value from the keyboard. I have already solved the problem of when a user inputs a string, so that is not the problem! Now I need to solve the problem of when a user inputs a mixed type. Here is an example of what I mean, the script:
------------------------------------------------------------------------------------------------------
#include <iostream>
#include "CinHelp.h"
int main()
{
int p;
double r;
CinHelp myin;
cout << "Enter an int: ";
p = myin.getInt();
cout << p << endl;
cout << "Enter a double: ";
r = myin.getDouble();
cout << r << endl;
return (0);
}
------------------------------------------------------------------------------------------------------
This script uses a class I wrote to deal with the case where a user enters a string such as 'pizza' instead of a number. The class:
------------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class CinHelp
{
public:
int getInt()
{
int inpt;
cin >> inpt;
while (cin.fail())
{
cout << endl
<<"Looking for an integer (1, 2, 3, etc.). Try again. ";
cin.clear();
cin.ignore(INT_MAX, '\n');
cin >> inpt;
}
return(inpt);
}
double getDouble()
{
double inpt;
cin >> inpt;
while (cin.fail())
{
cout << endl
<<"Looking for a number (1, 2.3, etc.). Try again. ";
cin.clear();
cin.ignore(INT_MAX, '\n');
cin >> inpt;
}
return(inpt);
}
};
------------------------------------------------------------------------------------------------------
This solves the problem of a user doing something like:
Enter an int: pizza
but it does not solve the problem of a user doing something like:
Enter an int: 44tre
If you copy these and run them, you will see that the characters are stuck in the stream somehow and end up messing with the next cin call. Can anyone please help me modify my CinHelp class to deal with this situation? I have no programming experience at all as of 3 weeks ago, I am learning completely on my own, so sorry if this is a really stupid question!
Thanks.
|