C++ 检查数字是否为 int/float

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/784563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:16:24  来源:igfitidea点击:

C++ check whether is number is int/float

c++

提问by Konrad Rudolph

i'm new here. i found this site on google.

我是新来的。我在谷歌上找到了这个网站。

#include <iostream>

using namespace std;

void main() {

    // Declaration of Variable
    float num1=0.0,num2=0.0;

    // Getting information from users for number 1
    cout << "Please enter x-axis coordinate location : ";
    cin >> num1;

    // Getting information from users for number 2
    cout << "Please enter y-axis coordinate location : ";
    cin >> num2;

    cout << "You enter number 1 : " << num1 << " and number 2 : " << num2 <<endl;

I need something like, when users enter alphabetical characters, it would display an error says, you should enter numbers.

我需要这样的东西,当用户输入字母字符时,它会显示一个错误,说你应该输入数字。

Any help greatly appreciated

非常感谢任何帮助

回答by Konrad Rudolph

First, to answer your question. This is actually very easy and you don't need to change much in your code:

首先,回答你的问题。这实际上非常简单,您不需要对代码进行太多更改:

cout << "Please enter x-axis coordinate location : " << flush;
if (!(cin >> num1)) {
    cout << "You did not enter a correct number!" << endl;
    // Leave the program, or do something appropriate:
    return 1;
}

This code basically checks whether the input was validly parsed as a floating point number – if that didn't happen, it signals an error.

这段代码主要检查输入是否被有效解析为浮点数——如果没有发生,它表示一个错误。

Secondly, the return type of mainmustalwaysbe int, never void.

其次, 的返回类型main必须始终int,从不void

回答by piotr

I'd use the cin.fail() approach or Boost "lexical cast" with propper use of exceptions to catch errors http://www.boost.org/doc/libs/1_38_0/libs/conversion/lexical_cast.htm

我会使用 cin.fail() 方法或 Boost“词法转换”并正确使用异常来捕获错误http://www.boost.org/doc/libs/1_38_0/libs/conversion/lexical_cast.htm

回答by Blair Zajac

Use something like

使用类似的东西

if (static_cast<int>(num1) == num1) {
  // int value
}
else {
  // non-integer value
}

回答by Steven

If you want to check input for integer/float/neither you should not use cin into a float. Instead read it into a string and you can check whether or not the input is valid.

如果要检查整数/浮点数/两者的输入,则不应将 cin 用于浮点数。而是将其读入字符串,您可以检查输入是否有效。

If cin reads an invalid number it will go into a failed state, which can be checked with if(cin.fail())

如果 cin 读取到无效数字,它将进入失败状态,可以使用 if(cin.fail()) 检查

However it is easier to read the input as a string and then convert the input to an integer or floating point number afterwards.

然而,更容易将输入作为字符串读取,然后将输入转换为整数或浮点数。

isdigit(c) should be called on a character not an an integer. For example isdigit('1') (Note the quotes).

isdigit(c) 应该在字符而不是整数上调用。例如 isdigit('1') (注意引号)。

you can use strtol to attempt to convert a string to an integer. Depending on the result you can then attempt to convert to floating point.

您可以使用 strtol 尝试将字符串转换为整数。根据结果​​,您可以尝试转换为浮点数。

回答by dreamlax

Although others have already answered the question, I'd just like to point out what isdigitis really used for. It tells you whether a given character represents a number or not.

虽然其他人已经回答了这个问题,但我只想指出isdigit真正用于什么。它告诉你一个给定的字符是否代表一个数字。

Basically, the definition of isdigitmay be:

基本上,的定义isdigit可能是:

int isdigit (int c)
{
    if (c >= '0' && c <='9')
        return 1;
    else
        return 0;
}

Then, if you have a string "asdf1234", you can check each character individually to test if it is a digit/number:

然后,如果您有一个 string "asdf1234",您可以单独检查每个字符以测试它是否是数字/数字:

char *test = "asdf1234";
int i;

for (i = 0; i < strlen (test); i++)
{
    if (isdigit (test[i]))
        fprintf (stdout, "test[%d] is a digit!\n", i);
}

回答by drarc

The input will be cast to fit the variable you're storing with cin. Because you're using cin on num1 and num2 (which are floats), no matter what number the user enters (to a degree), it will be a float.

输入将被强制转换以适合您使用 cin 存储的变量。因为您在 num1 和 num2(它们是浮点数)上使用 cin,所以无论用户输入什么数字(在一定程度上),它都将是一个浮点数。

回答by Abhay

Always read the number in a string and check the same as below:-

始终读取字符串中的数字并检查与以下相同的内容:-

template <class out_type, class in_type>
out_type convert(in_type const& t)
{
  std::stringstream stream;
  stream << t; // insert value to stream
  // store conversion's result here
  out_type result;
  stream >> result; // write value to result
  // if there is a failure in conversion the stream will not be empty
  // this is checked by testing the eof bit
  if (! stream.eof() ) // there can be overflow also
  { // a max value in case of conversion error
    result = std::numeric_limits<out_type>::max();
  }
  return result;
}

It is used as

它被用作

int iValue = convert<int>(strVal);
if (std::numeric_limits<int>::max() == iValue)
{
  dValue = convert<double>(strVal);
}

This is a little modern way of doing it :-)

这是一种现代的做法:-)

回答by Thomas Bonini

You can store the input into a string, and then create a function such as this:

您可以将输入存储到一个字符串中,然后创建一个函数,如下所示:

bool GetInt(const char *string, int *out)
{
    char *end;

    if (!string)
        return false;

    int ret_int = strtoul(string, &end, 10);

    if (*end)
        return false;

    *out = ret_int;
    return true;
}

GetInt("1234", &somevariable) returns true and sets somevariable to 1234. GetInt("abc", &somevariable) and GetInt("1234aaaa", &somevariable) both return false. This is the version for float by the way:

GetInt("1234", &somevariable) 返回 true 并将 somevariable 设置为 1234。 GetInt("abc", &somevariable) 和 GetInt("1234aaaa", &somevariable) 都返回 false。顺便说一下,这是浮动版本:

HOT RESULT_MUST_BE_CHKED NONNULL bool GetFloat(const char *string, float *out)
{
    char *end;

    if (!string)
        return false;

    float ret_float = (float)strtod(string, &end);

    if (*end)
        return false;

    *out = ret_float;
    return true;
}

回答by metaldog

//Just do a type cast check
if ((int)(num1) == num1){
//Statements
}

回答by Francisco Cortes

I wanted to validate input and needed to make sure the value entered was numeric so it could be stored on a numeric variable. Finally this work for me (source: http://www.cplusplus.com/forum/beginner/2957/

我想验证输入并需要确保输入的值是数字,以便它可以存储在数字变量中。最后这项工作对我有用(来源:http: //www.cplusplus.com/forum/beginner/2957/

int number;
do{
      cout<<"enter a number"<<endl;
      cin>>number;
      if ((cin.fail())) {
         cout<<"error: that's not a number!! try again"<<endl;
         cin.clear(); // clear the stream
         //clear the buffer to avoid loop (this part was what I was missing)
         cin.ignore(std::numeric_limits<int>::max(),'\n');
         cout<<"enter a number"<<endl; //ask again
         cin>>number;
      }

 } while (cin.fail());