简体   繁体   English

检查输入是否为整数或大于零

[英]Check if input is integer or above zero

so im struggling a bit - how can i make function to check if the user input is integer? 所以我有点挣扎-我如何使函数检查用户输入是否为整数? I did try do/while... but somehow its not working. 我确实尝试过/虽然...但是以某种方式无法正常工作。

void pievieno(int *a ,int jaunais,int vecais){
int jaunais_skaitlis;
cout<< "Ievadiet skaitlus" <<endl;
for (int i=vecais;i<jaunais;i++) 

{
    cin >> jaunais_skaitlis;
    a[i] = jaunais_skaitlis;
}

Thanks in advance! 提前致谢!

Well, there's no point in checking the data type of user's input because you've deliberately defined the input variable to be an integer using int jaunais_skaitlis; 嗯,检查用户输入的数据类型毫无意义,因为您已经使用int jaunais_skaitlis;故意将输入变量定义为整数int jaunais_skaitlis; . Therefore, no matter what the user types in, you're getting and integer value for the input anyways. 因此,无论用户键入什么内容,无论如何您都将获得整数值。

However, what you can do it define the data type to be something other than integer , maybe a float , and then check if its an integer, float or something else. 但是,您可以将数据类型定义为除integer其他数据(可能是float ,然后检查其是否为整数,float或其他类型。

You should accept user's input with string, and check what's in it. 您应该接受用户输入的字符串,并检查其中的内容。 There's lots of method to check user's input. 有很多检查用户输入的方法。 The most powerful way is regex. 最强大的方法是正则表达式。

When you call stream >> variable , depending of type of variable , the stream will try to process characters in order to get something, which is a valid for such variable type. 当你调用stream >> variable ,取决于类型的variable ,则stream将尝试按顺序处理的字符得到的东西,这是此类变量类型的有效。 If it fails to do so, stream s failbit is set, so you can check that. 如果失败,将设置stream的故障failbit ,以便您进行检查。

for (int i=vecais;i<jaunais;i++) 
{
    cin >> jaunais_skaitlis;
    if (cin.fail())
    {
        // abort, user inputed something, which is not integer.
    }
    a[i] = jaunais_skaitlis;
}

Beware, that stream will do as much as it can to actually extract something from the input. 当心,该stream将尽其所能从输入中实际提取某些内容。 Thus, if you enter 123qffe541e , it actually is valid input, jaunais_skaitlis will contain 123 and rest of characters will remain in the stream (thus, failing next iteration). 因此,如果输入123qffe541e ,它实际上是有效输入,则jaunais_skaitlis将包含123 ,其余字符将保留在流中(因此,在下一次迭代中失败)。

If you really want to check if whole input is integer, you have to read more chars (eg read to std::string , either single word or whole line, depending on your needs) and then process that. 如果您真的想检查整个输入是否为整数,则必须阅读更多的字符(例如,根据需要,读取到std::string ,可以是单个单词也可以是整行),然后对其进行处理。

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

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