c++ - cin 的十进制输入验证?

标签 c++ loops validation

我正在尝试验证用户输入的数组应该有多大。我正在检查是否 size < 1如果代码中有小数位,请使用:

int size = 0;
do {
    size = 0;
    cout << "Input an array size for your words array: ";
    cin >> size;
    if (floor(size) != size || size < 1) {
        cout << "Hey that's not a valid size!\n";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
} while (floor(size) != size || size < 1);

我遇到的问题是像 -1、0、.3 .9 这样的数字都可以正常验证,但是像 1.2 这样的数字会有 size == 1。然后 .2 留在队列中。有没有办法清除这些小数?我试过只使用 size < 1和 floor bool 值本身。

谢谢!

最佳答案

当用户输入类似“1.2”的内容并且您尝试从输入流中提取 int 时,流提取运算符 >>> 将成功提取 1 其余的留在输入流中。因此,您所要做的就是检查流中剩余的内容是否为空白以外的任何内容。

#include <limits>
#include <cctype>
#include <iostream>

// This function peeks at the next character in the stream and only re-
// moves it from the stream if it is whitespace other than '\n'.
std::istream& eat_whitespace(std::istream &is)
{
    int ch;
    while ((ch = is.peek()) != EOF &&
           std::isspace(static_cast<unsigned>(ch)) && // Don't feed isspace()
           ch != '\n')                                // negative values!
    {
        is.get();
    }
    return is;
}

int main()
{
    int size;
    bool valid{ false };
    while (std::cout << "Input an array size for your words array: ",
           !(std::cin >> size >> eat_whitespace) ||
           size < 1 ||
           std::cin.get() != '\n') // since all whitespace has been eaten up
                                   // by eat_whitespace, the next character 
                                   // should be a newline. If it is not there 
                                   // is some other garbage left in the stream.
    {
        std::cerr << "Hey that's not a valid size!\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

关于c++ - cin 的十进制输入验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909885/

相关文章:

javascript - react .map 不渲染

arrays - Laravel 5 数组验证

c++ - 为什么 vector::erase 似乎会导致崩溃?

c++ - dynamic_cast 由 lt_dlopen(libtool) 加载的共享库中的接口(interface)不起作用

c++ - 非静态成员变量创建类似于 C++ 中的静态单例创建

c++ - 用户空间中的内存障碍? (Linux,x86-64)

linux - 在文件夹中运行 "N"Shell 脚本

javascript - Bootstrap 4 表单验证

jquery - JQuery Validation SubmitHandler 和 Form.Submit 成功后如何阻止输入?

c++ - 指向非静态成员函数的指针的值