验证整数输入C ++? [英] validate integer input C++?

查看:57
本文介绍了验证整数输入C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用!(cin>>输入)来验证整数输入,但它无法捕获其他数据类型,例如浮点数.取而代之的是第一个整数.EG:

I use !(cin >> input) to validate integer input, but it does not catch other datatypes such as floats. Instead it takes the first whole number. EG:

请输入数字:2.5.

Please enter a number: 2.5.

我的错误消息出现在这里,应该是循环循环,但取第一个数字.

My error message appears here, it is suppose to loop round but it takes first number instead.

输出"2"

如何忽略小数输入?

推荐答案

输入流将以符号开头,后跟至少一个十进制数字的任何内容视为有效的整数输入.如果要在包含小数点的十进制输入上失败,则需要做一些其他的事情.一种读取整数并查看成功读取整数后的字符是否为小数点的方法:

The input stream considers anything starting with a sign followed by at least one decimal digit to be a valid integer input. If you want to fail on a decimal input including a decimal point, you need to do something different. One way to deal with this to read an integer and see if the character following the successful read of an integer is a decimal point:

if (!(std::cin >> value)
    || std::cin.peek() == std::char_traits<char>::to_int_type('.')) {
    deal_with_invalid_input(std::cin);
}

正如托马斯·马修斯(Thomas Matthews)正确指出的那样,问题实际上并不仅限于浮点数,而是任何带有数字前缀且后跟非空格的数字(而不是EOF:上述解决方案实际上会在文件的末尾,即不跟任何东西,甚至没有换行符).要只读取整数,后跟一个空格或文件的末尾,则顺序如下:

As Thomas Matthews correctly pointed out, the problem isn't really limited to floating point numbers but anything with a prefix of digits followed by a non-space (and not EOF: the above solution would actually miss a valid integer at the very end of a file, i.e., not followed by anything, not even a newline). To only read integers followed by a space or at the end of a file, something like this would be in order:

if (!(std:cin >> value)
    || (!std::isspace(std::cin.peek())
        && std::cin.peek() != std::char_traits<char>::eof())) {
    deal_with_invalid_input(std::cin);
}

实际上没有任何方法可以返回已经读取的字符.由于在很多地方都不太好用,因此将此功能打包到合适的 std :: num_get< char> 方面和 imbue()流以及相应的 std :: locale .尽管处理代码的表达式实际上更简单了,但它还是有点高级.

There isn't really any way to return the already read characters. Since this isn't really nice to be used in many places, it may be reasonable to package this function into a suitable std::num_get<char> facet and imbue() the stream with a corresponding std::locale. This is a bit more advanced although the expression to deal with the code is actually simpler.

这篇关于验证整数输入C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆