检查cin int是否仅包含数字?

问题描述 投票:1回答:1

这不是重复的问题,我不想验证字符串,我想验证整数。

我进行了一些研究,发现的代码示例使用类似的方法来检查输入是否严格为整数。

我看到的代码看起来像这样

while(1) { // <<< loop "forever"
    cout << "Please enter an integer.";
    cin >> n;

    if (cin.good())
    {
        if (n < 0) {cout << "Negative.";}
        else { cout << "Positive."; break; }
    }                            // ^^^^^ break out of loop only if valid +ve integer
    else
    {
        cout << "Not an integer.";
        cin.clear();
        cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
    }
}

cout << "\ndone.";

问题是,如果您运行该代码并键入5j,也将被接受

[我发现了一个叫做isdigit()的东西,但它只检查一个数字,我想检查说123的输入,并确保只输入数字。

在C ++中,执行此验证的方法是什么

c++ validation cin extraction istream
1个回答
0
投票

默认的C ++输入是基于流的,而不是基于行的。如果要基于行处理输入,则必须从流中读取整个行,然后再处理这些行。对于您的特定用例,它可能看起来像这样:

while(1) { // <<< loop "forever"
    cout << "Please enter an integer.";
    std::string line;
    std::getline(cin, line, '\n');

    std::istringstream str(line);
    str >> n;
    if (str && str.eof())
    {
        if (n < 0) {cout << "Negative.";}
        else { cout << "Positive."; break; }
    }                            // ^^^^^ break out of loop only if valid +ve integer
    else
    {
        cout << "Not an integer.";
        cin.clear();
        cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
    }
}

cout << "\ndone.";
© www.soinside.com 2019 - 2024. All rights reserved.