BigBoB
BigBoB

Reputation:

C++ check whether is number is int/float

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

Upvotes: 8

Views: 62393

Answers (10)

Francisco Cortes
Francisco Cortes

Reputation: 1226

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/

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

Upvotes: 0

metaldog
metaldog

Reputation: 71

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

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 546153

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.

Upvotes: 18

piotr
piotr

Reputation: 5745

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

Upvotes: 7

Andreas Bonini
Andreas Bonini

Reputation: 44832

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:

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;
}

Upvotes: 0

Abhay
Abhay

Reputation: 7190

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

Upvotes: 1

dreamlax
dreamlax

Reputation: 95405

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.

Basically, the definition of isdigit may be:

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:

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

Upvotes: 3

Steven
Steven

Reputation: 3928

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.

If cin reads an invalid number it will go into a failed state, which can be checked with 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).

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.

Upvotes: 4

drarc
drarc

Reputation: 248

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.

Upvotes: 2

Blair Zajac
Blair Zajac

Reputation: 4655

Use something like

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

Upvotes: 7

Related Questions