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