如何忽略用户输入的任何字符串?

How can I ignore any string that the user inputs?

用户应该输入一个双精度数,但是如果他们输入一个字符串或字符,我如何让程序忽略它。我当前代码的问题是当我输入一个字符串时程序将垃圾邮件并填充带有 cout << "What is the length of the rectangle";

的屏幕
double length;

do {
    cout << "What is the length of the rectangle: ";
    cin >> length;
    bString = cin.fail();
} while (bString == true);

如果用户输入了无效的数据类型,cin 将失败。你可以用这个

检查
double length;
while(true)
{
    std::cout << "What is the length of the rectangle: ";
    std::cin >> length;

    if (std::cin.fail())
    {
        std::cout << "Invalid data type...\n";
        std::cin.clear();
        std::cin.ignore();
    }
    else
    {
        break;
    }
}

cin.fail()不会区分整数和浮点数。

最好的检查方法是使用 std::fmod() 函数检查提醒是否大于零。如果是那么它是一个浮点数。

这是代码

#include <cmath>

int main()
{
    double length;
    std::cout <<"What is the length of the rectangle: ";
    std::cin >> length;

    if (std::cin.fail())
    {
        std::cout<<"Wrong Input..."<<std::endl;
    } else 
    {
        double reminder = fmod(length, 1.0);
        if(reminder > 0)
           std::cout<<"Yes its a number with decimals"<<std::endl;
        else
            std::cout<<"Its NOT a decimal number"<<std::endl;
    }
}

请注意,此代码不会区分 12 和 12.0。

do {
    cout << "What is the length of the rectangle: ";
    cin >> length;
    bString = cin.fail();
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (bString == true);

这是我找到的适用于我的问题的代码。