C ++检查number是否为int / float

时间:2022-01-20 20:56:20

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

任何帮助非常感谢

10 个解决方案

#1


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 main must always be int, never void.

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

#2


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“lexical cast”,使用异常来捕获错误http://www.boost.org/doc/libs/1_38_0/libs/conversion/lexical_cast.htm

#3


Use something like

使用类似的东西

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

#4


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尝试将字符串转换为整数。根据结果​​,您可以尝试转换为浮点。

#5


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

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

Basically, the definition of isdigit may 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:

然后,如果你有一个字符串“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);
}

#6


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,无论用户输入什么数字(在某种程度上),它都是浮点数。

#7


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 :-)

这是一种现代的方式:-)

#8


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并将somevarset设置为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;
}

#9


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

#10


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());

#1


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 main must always be int, never void.

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

#2


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“lexical cast”,使用异常来捕获错误http://www.boost.org/doc/libs/1_38_0/libs/conversion/lexical_cast.htm

#3


Use something like

使用类似的东西

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

#4


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尝试将字符串转换为整数。根据结果​​,您可以尝试转换为浮点。

#5


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

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

Basically, the definition of isdigit may 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:

然后,如果你有一个字符串“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);
}

#6


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,无论用户输入什么数字(在某种程度上),它都是浮点数。

#7


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 :-)

这是一种现代的方式:-)

#8


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并将somevarset设置为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;
}

#9


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

#10


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());