1. ## Preventing overflow

Suppose I want to accept input of an int variable. I would like the program to quit if the number input is beyond the range of the int data type. What would be the best way to do this?

2. It depends on the input of the variable. Can it be represented as a hexadecimal value? Can it be negative? Assuming length of input string can be formatted (0x, etc) and inifite, no pure and simple solution comes to my mind.

You can load this into a larger data type and then check, but I think that the best solution would be a custom string parser.

3. This is what I tried. The number is an unsigned long, and for some reason, this conditional statement is not triggered.

Code:
```    if (x < 0 || x > 4294967295) {
cout <<" Number has to be from 0 to 4,294,967,295.";
return -1;
}```

4. Because size of long = int in this case.

Think, if x is unsigned, how can it be less than 0..

5. Yeah, I was trying to restrict the possible size of input to be processed, but still, I don't know what to do if something like a negative number is input. Something beyond cin has to intercept the input...

6. You can first read this into a string.

Then perform a conversion using a stringstream. Then you can perform all kinds of checks on the input.

Code:
```#include <string>
#include <iostream>
#include <sstream>
#include <cctype>

{
std::string input;
std::cin >> input;
if (input[0] == '-') { //streams will happily read negative values into unsigned types
return false;
}
std::stringstream ss(input);
if (! (ss >> out) ) {  //input is not a number at all
return false;
}
if (!ss.eof()) {
char ch;
ss >> ch;
return !isdigit(ch);  //at least one unread digit - overflow
}
return true;
}

int main()
{
unsigned long n;
while (true) {
std::cout << "Enter unsigned integer: ";
std::cout << n << '\n';
break;
}
else {
}
}
}```
Example run:
Code:
```Enter unsigned integer: abc
Enter unsigned integer: -123
Enter unsigned integer: 123456678901234567890