Is there any way to not letting cin execute when user input char instead of int/ double?

closed account (Sh59216C)
1
2
3
4
5
6
7
8
9
10
11
12
13
         
          cout << "Please enter the stock ticker: ";
          cin >> ticker;
          cout << "\nPlease enter latest price: ";
          cin >> price;
          cout << "\nPlease enter latest 50-day moving average: ";
          cin >> ma50;
          cout << "\nPlease enter latest 200-day moivng average: ";
          cin >> ma200;
          cout << "\nPlease enter latest EPS: ";
          cin >> EPS;

          


TICKER IS A STRING

PRICE MA50, 200 EPS ARE ALL double
I also wish to reject any negative input
Put each input to cin in a loop, check to see if the input variable is negative, and prompt the user to re-enter the values if the input values are negative. I'm assuming this is homework, so that's really all I'm going to say.
closed account (j2NvC542)
I'd suggest a do-while loop for that.
For, example
1
2
3
4
5
do
{
       cout << "\nPlease enter latest price: ";
       cin >> price;
}while(price < 0)

for char you need to use isdigit().
closed account (Sh59216C)
I mean the code for while input not equal to int
I tried if(x!= int) and it obviously would not work,, any other thoughts?


I see isdigit.
if(isdigit(x))
it will return true if x is digit(probably integer).
closed account (Sh59216C)
Thank you!!!!
closed account (Sh59216C)
How about if the data type is double?
When you do:
1
2
int i; // or double i
cin >> i;


and the user enters a non-number, the user causes the fail bit to be set for cin. In order to fix this you must first clear(), then ignore() everything in the buffer, and finally ask for the number again:
1
2
3
4
5
6
7
8
9
10
11
12
double d; // or int d
cout << "Please enter an integer: ";
while (!(cin >> d))  // while the extraction sets the fail bit
{
  cin.clear();
  cin.ignore(80, '\n');
  cout << "Numbers only please, try again: ";
}
cin.ignore(80, '\n');  // ignore when the loop is finished too

if (d != static_cast<int>(d))
  cout << "Hey, I asked for an integer!\n";
Topic archived. No new replies allowed.