我正在尝试验证用户输入的数组应该有多大。我正在检查是否 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/