1

I have received a task that does not actually specify, what range of input one of my functions should expect (only, that it is always going to be a positive integer), and the input is decided runtime. Can I somehow test if the type I selected can actually hold the value it was fed to?

An illustration of what I am hoping to do:

char test;
std::cin >> test;
if(MAGIC)
{
    std::cout << "Error." << std::endl;
} 

With the magical part (or even the preceeding line) being the test I'm looking for. It should work like this:

stdin: 100 -> no output

stdin: 1000000 -> Error.

Community
  • 1
  • 1
Adam Hunyadi
  • 1,770
  • 11
  • 26
  • 1
    related: https://stackoverflow.com/questions/3582509/why-does-integer-overflow-cause-errors-with-c-iostreams – scohe001 Nov 14 '17 at 16:42

2 Answers2

3

For most data types you can check the error state of the input stream as described here. However, this would not work for some other types, such as char from your post, because std::cin >> test would read data as a single character, i.e. '1' which is not what you need to achieve.

One approach is to read the number into std::string, and compare it to the max() obtained through limits:

std::string max = std::to_string(std::numeric_limits<char>::max());
std::string s;
std::cin >> s;
bool cmp = (s.size() == max.size()) ? (s <= max) : (s.size() < max.size());
std::cout << s << " " << cmp << std::endl;

Demo.

Note: The above code makes an assumption that the data entered is a number, which may be arbitrarily large, but must not contain characters other than digits. If you cannot make this assumption, use a solution from this Q&A to test if the input is numeric.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
2

I think the answer may be in https://stackoverflow.com/a/1855465/7071399 to know where to get the limits, then refer to https://stackoverflow.com/a/9574912/7071399 to get inspiration to your code (given you can use a long int or a char array to store the number and then check if it fits in the integer value).