简体   繁体   English

输入验证int C ++

[英]Input Validation of int C++

I basically want to validate that I have an int and not a floating point number. 我基本上想验证我有一个整数而不是一个浮点数。 What I currently have is: 我目前拥有的是:

int den1;
cout << "Enter denominator of first fraction" << endl;
cin >> den1;
while (den1 == 0){
   cout << "Enter a non-zero denominator" << endl;
   cin >> den1;
}

Is there a "test" to generate a boolean value for den1 == int? 是否有一个“测试”为den1 == int生成布尔值? I'm trying to avoid using getline() because I don't want to use a string if it isn't necessary. 我试图避免使用getline(),因为如果不需要,我不想使用字符串。

If you want to force your input to be of an integer type, then use an integer type for your input. 如果要强制输入为整数类型,请对输入使用整数类型。 If den1 is an int , it will not let you put a floating point value in it. 如果den1是一个int ,它将不允许您将浮点值放入其中。 That is, cin >> den1 will be an int value. 也就是说, cin >> den1将是一个int值。 If the user tries to input 3.14159 , only the 3 will be read (it will stop reading at the . . Note that the rest of the buffer will contain numbers as well, so if you don't clear it, the next attempt to read an integer will read 14159 . 如果用户试图输入3.14159 ,只有3将被读取(它会停在读书.需要注意的是缓冲区的其余部分将包含数字一样,所以如果你不明确的话,下一次尝试阅读整数将读取14159

EDIT 编辑

If you want to "force" the user to enter a valid integer, you can do something like this: 如果要“强制”用户输入有效的整数,则可以执行以下操作:

std::string line; std :: string行;

int value = 0;
bool valid = false;
do
{
    if (std::getline(std::cin, line))
    {
        if (std::string::npos == line.find('.'))
        {
            // no decimal point, so not floating point number
            value = std::stol(line);
            valid = true;
        }
        else
        {
            std::cin.clear();
        }
    }
} while (!valid);

Which is a lot of extra code compared to: 与以下内容相比,这是很多额外的代码:

int value;
std::cin >> value;

You want to use something like 您想使用类似

if (std::cin >> den) {
    // process den
}
else {
    // deal with invalid input
}

When an input operation fails, it sets std::ios_base::failbit on the stream and the stream converts to false instead of true . 当输入操作失败时,它将在流上设置std::ios_base::failbit ,并且流将转换为false而不是true While the stream is in this failure mode, it won't read anything from the stream, ie, the failure mode as to be cleared, eg, using 当流处于此故障模式时,它将不会从流中读取任何内容,即要清除的故障模式,例如,使用

std::cin.clear();

Once the failure mode is cleared, the offending character still sits in the stream. 清除故障模式后,有问题的角色仍会位于流中。 You can ignore the next character using, eg 您可以使用例如忽略下一个字符

std::cin.ignore();

or ignore all characters until the next newline: 或忽略所有字符,直到下一个换行符为止:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

First of all, user input is always a string. 首先,用户输入始终是字符串。 Next, you need to define your goal more precisely. 接下来,您需要更精确地定义目标。 For example a reasonable thing to distinguish is whether the input can be parsed in its entirety as an integer, or as a floating point number, or neither. 例如,一个合理的区分是输入是否可以完整地解析为整数,浮点数或两者都不解析。 Here's one way to do this with iostreams, disregarding whitespace: 这是使用iostream做到这一点的一种方法,而无需考虑空格:

#include <iostream>
#include <sstream>
#include <string>

for (std::string line; std::getline(std::cin, line); )
{
    std::istringstream iss1(line), iss2(line);
    int n;
    double x;

    if (iss1 >> n >> std::ws && iss1.get() == EOF)
    {
        // have an int, use "n"
    }
    else if (iss2 >> d >> std::ws && iss2.get() == EOF)
    {
        // have a floating point number, use "d"
    }
    else
    {
        // failed to parse the input
        continue;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM