检查值为int或string

时间:2016-07-02 17:30:20

标签: c++

我试图找到用户输入的值是String或Int,但是当用户输入任何字符串时程序卡在循环中。如果是,那么我删除int taxableIncome值一次执行然后如何? 我是初级程序员...... 无论如何我告诉我,我可以检查用户的值是int还是string .... 这是代码

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;
    }
}

1 个答案:

答案 0 :(得分:3)

cin >> taxableIncome失败后(您正在检测)cin的进一步读取将直接失败,因为该流已标记其bad位。你需要清除那一点,咀嚼剩余的线,然后再试一次。

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');
    }
}