代码之家  ›  专栏  ›  技术社区  ›  Rage Games

我怎么能忽略用户输入的任何字符串?

  •  -1
  • Rage Games  · 技术社区  · 7 年前

    用户应该输入一个double,但是如果他们输入一个字符串或字符,我如何让程序忽略它们呢。我当前代码的问题是,当我输入一个字符串时,程序会发出垃圾邮件,并在屏幕上填充cout<&书信电报;“矩形的长度是多少”;

    double length;
    
    do {
        cout << "What is the length of the rectangle: ";
        cin >> length;
        bString = cin.fail();
    } while (bString == true);
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   Werner Henze    7 年前
    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);
    

    这是我发现的适用于我的问题的代码。

        2
  •  0
  •   DeepakKg    7 年前

    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。

        3
  •  -1
  •   State    7 年前

    如果用户输入的数据类型无效,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;
        }
    }