c++ - 一种不接受 float 作为输入的方法 C++

标签 c++ input floating-point int

我正在做一个项目,我需要检查输入是否正确 (n),我目前有一些代码不允许输入字符串,因为它会再次要求输入正确的数量。我在编写不允许 float 通过的代码时遇到问题,因为它目前只是忽略了输入的浮点部分。如果这是一个简单的问题,我很抱歉,但我还没有找到解决这个问题的方法。

  for(int i=0; i<1; ++i)
    {
        string b1;
        int e;
        do
        {
            getline(cin,b1);
            e=atoi(b1.c_str());
        }
        while(e==0 && b1!="0");
        n=e; // where n is the user input
    }

最佳答案

假设您考虑任何带有小数点 ('.') 或使用带负指数的科学记数法作为 Not Acceptable float ,只需检查输入的字符串是否包含以下之一:

std::string::iterator it;
if (b1.end() != std::find(b1.begin(), b1.end(), '.')
    || (b1.end() != (it = std::find_if(b1.begin(), b1.end(),
                                       [](char c){ return c == 'e' || c == 'E'; })
        && it + 1 != b1.end()
        && '-' == it[1])) {
    // deal with the string being a floating point number with a fractional part
}

请注意,这会将例如 "10e-1" 视为错误值,尽管它实际上只是 "1" 的奇特拼写。

关于c++ - 一种不接受 float 作为输入的方法 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33986621/

相关文章:

c++ - 学习 C++ : why is this illegal?

c++ - 使用cin函数在c++中输入数学运算

java - 如何在 java.swing JTextField 中存储字符串或整数?

c - 如何获得 10 次方的 double 的尾数和指数?

c++ - SFML 全屏和居中

c++ - 如何使用 C++ 模板模拟高阶函数?

c++ - 如何在 C++ 中获得整数类型的无符号等价物?

c - 将键盘输入存储到C中的整数数组中

c++ - 显然相同的数学表达式具有不同的输出

assembly - 从x86-64打印 float 似乎需要保存%rbp