我如何检查输入是否是C ++中的int?

时间:2014-05-07 02:00:58

标签: c++

如果输入是整数,我想将其设置为整数变量。

如果输入是一个字符串,我想将它设置为一个字符串变量,然后检查字符串是否为"退出"。

我不知道如何检查它。我找了一个内置函数,什么都没发现。

while (true) {

    int numberEntered;
    string stringEntered; 

    cout << "enter a number to see if it is greater than 5: \n or enter \'quit\' to exit the program";

    //I don't know what to do below here
    cin >> ;

    if (stringEntered == "quit") {
        break;
    }

    if (numberEntered > 5) {
        cout << "that number is greater than 5" << endl;
    }
    else {
        cout << "not greater than 5" << endl;
    }
}

2 个答案:

答案 0 :(得分:2)

cin >> numberEntered;
if (!cin.fail())
{
   ...

使用它可能更惯用:

if (cin >> numberEntered)

答案 1 :(得分:0)

David S.的答案很好。如果你想整齐地处理在行之后输入的垃圾,这里是另一个选项(这对你的情况来说更复杂,但是如果你以后想扩展你的程序来处理很多不同的输入,那么这种方式可能会出现更简单)。

while( true )
{
    string stringEntered;
    cout << "enter a number to see if it is greater than 5: \n or enter \'quit\' to exit the program: " << flush;

// read the whole line, this ensures no garbage remains in the input stream
    getline(cin, stringEntered);

    if ( stringEntered == "quit" )
        break;

// this checks that a number was entered and nothing else
    istringstream iss(stringEntered);
    int numberEntered;
    char ch;
    if ( !(iss >> numberEntered) || (iss >> ch) )
    {
        cout << "please try again. ";
        continue;
    }

// process the number
    cout << "that number is " << (numberEntered > 5 ? "" : "not ")
            << "greater than 5." << endl;
}

您可能需要#include <sstream>