我正在尝试验证用户输入的数组大小。我正在使用以下命令检查是否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
和下限布尔值。
谢谢!
答案 0 :(得分:1)
当用户输入“ 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');
}
}