Gaurav K
Gaurav K

Reputation: 2975

Disabling Implicit Casting in c++

Is it possible to disable implicit casting in C/C++.

Suppose I want to write a validity function that makes me enter only integers in range [1,10]

I have written:

#include <iostream>


using namespace std;

int main( )
{
    int var=0;
    cout << "Enter a number (Integer between 1 to 10) : ";

    while( (!(cin >> var )) || (var > 10 ) || (var < 1) )
    {
        cout << "U nuts .. It can only be [1,10]\n";
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        cout << "Enter a number (Integer between 1 to 10) : ";
        }

    cout << "\nYou entered : " << var;

   return 0;
}

But if the user enters 9.5 it accepts it by converting the float 9.5 as 9 and storing it in var. I want any float entry to be treated as invalid entry. How do I achieve this most compactly.

I do not want to do something of this sort:

#include <iostream>
#include <cmath>


using namespace std;

int main( )
{
    float var=0;
    cout << "Enter a number (Integer between 1 to 10) : ";

    while( (!(cin >> var )) ||(var < 1)|| (var > 10 ) || !(ceilf(var) == var) )
    {
        cout << "U nuts .. It can only be [1,10]\n";
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        cout << "Enter a number (Integer between 1 to 10) : ";
        }

    cout << "\nYou entered : " << var;

   return 0;
}

This serves my purpose . But what I want to know, that is there any way where a conversion from float to int - I can suppress or it can show it as false input.

Similar to the way cin >> var where var type is int - if we enter char it returns false condition. Can we achieve the same for float entry ?

Thanks

Upvotes: 3

Views: 2102

Answers (2)

Steve Jessop
Steve Jessop

Reputation: 279255

But if the user enters 9.5 it accepts it by converting the float 9.5 as 9 and storing it in var.

No it doesn't. If the the user enters 9.5, then cin >> var stops reading when it hits the . (and leaves it on the stream). There's no float-to-int conversion because you haven't read a float, just an int.

The fix is to read the rest of the input (after cin >> var), and make sure there's nothing bad left over after the end of the int.

Upvotes: 6

ronalchn
ronalchn

Reputation: 12335

If you want to validate all of the input, you will have to get the whole line first.

Try:

string line;
getline(cin, line); // gets whole line
char *endptr;
long int var = strtol(line.c_str(), &endptr, 10); // converts string to int

// now check that endptr points to end of the string
if (endptr<line.c_str()+line.length()) {
  // extra characters found after the integer
}

Upvotes: 1

Related Questions