如何禁止包含非数字?

How to forbid the inclusion of non-numbers?

我有这个程序:

#include <iostream>
#include <string>

using namespace std;

int main()
{
int i=0;
float reader,  tot = 0;

while(i!=10)
{
    cout << "Insert a number: " << endl;
    cin >> reader;

    if(cin)
    {
        tot += reader;
        i++;
    }

    else
    {
        cout << "Error. Please retry." << endl;
        cin.clear();
    }
}

cout << "Media: " << tot/i << endl;

return 0;
}

在 IF() 中,我希望用户在 "reader" 变量中仅插入浮点值。 我希望如果用户插入一个数字,程序会继续...否则程序应该重新要求用户插入正确的值。

如何检查输入?我尝试使用 TRY CATCH,但没有用。

提前致谢!

只需检查operator>>的结果:

if (cin >> reader) {
    // user gave you a float
    tot += reader;
    i++;
}
else {
    cout << "Error. Please retry." << endl;

    // clear the error flag on cin, and skip
    // to the next newline.
    cin.clear(); 
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

"How to do this checking the INPUT?"

已经保证了
cin >> reader;

用户只能输入有效的 float 值。检查有效性的方法是

if( cin >> reader ) {
   tot += reader;
   i++;
}
else {
   cout << "Error. Please retry." << endl;
   cin.clear();
   std::string dummy;
   cin >> dummy; // <<< Read invalid stuff up to next delimiter
}

这是 fully working sample


"I tried with a TRY CATCH but it didn't work."

要从 std::istream 操作中获取异常,请设置 std::istream::exceptions 掩码。

您的原始程序很好,只是您在遇到错误时需要跳过错误的输入。仅仅清除错误是不够的:

#include <iostream>
#include <string>
#include <limits> // include this!!!

using namespace std;

int main()
{
int i=0;
float reader, tot = 0.0f; // tot needs to be float

while(i!=10)
{
    cout << "Insert a number: " << endl;

    if( cin >> reader )
    {
        tot += reader;
        i++;
    }
    else
    {
        cout << "Error. Please retry." << endl;
        cin.clear();
        // Then you ned to skip past the bad input so you
        // don't keep tripping the same error
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

cout << "Media: " << tot/i << endl;

return 0;
}

函数 cin.ignore() 忽略尽可能多的输入字符,直到行尾字符 '\n'std::numeric_limits<std::streamsize>::max() 函数告诉我们可以存储在输入缓冲区中的最大可能字符数。

如果它令人困惑,跳过错误输入的另一种方法是简单地将下一行读入 std::string

    else
    {
        cout << "Error. Please retry." << endl;
        cin.clear();
        // Then you need to skip past the bad input so you
        // don't keep tripping the same error
        std::string skip;
        std::getline(cin, skip); // read the bad input into a string
    }