0

I'm trying to find that entered value from the user is String or Int,but program stuck in a loop when a user entered any string.Can I delete int taxableIncomevalue one-time execution if yes then how ? I'm beginner level programmer... tell me anyway within that I can check Value from user is int or string.... here is code

int taxableIncome;

for (;;) {
    cout << "Please enter in your taxable income: ";
    if (cin >> taxableIncome) {
        cout << "Your income: " << taxableIncome;
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
    }
}
Kamal Mrock
  • 374
  • 1
  • 2
  • 13

1 Answers1

3

Once cin >> taxableIncome fails (which you're detecting) further reads from cin will fail directly because the stream is already flagged with its bad bit. You need to clear that bit, munch the rest of the line, and try again.

int taxableIncome;

for (;;) {
    cout << "Please enter in your taxable income: ";
    if (cin >> taxableIncome) {
        cout << "Your income: " << taxableIncome;
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}
WhozCraig
  • 65,258
  • 11
  • 75
  • 141