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

Aug 8, 2012 at 5:46am
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
Aug 8, 2012 at 5:59am
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.
Aug 8, 2012 at 6:07am
closed account (j2NvC542)
I'd suggest a do-while loop for that.
Aug 8, 2012 at 6:15am
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().
Aug 13, 2012 at 10:43pm
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.
Aug 14, 2012 at 4:47am
if(isdigit(x))
it will return true if x is digit(probably integer).
Aug 14, 2012 at 6:36am
closed account (Sh59216C)
Thank you!!!!
Aug 14, 2012 at 6:38am
closed account (Sh59216C)
How about if the data type is double?
Aug 14, 2012 at 5:12pm
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.