Dear friends. How am i going to check if an input (integer in this case) by string stream exceeds the systems limits. I can inquire what this limit is by using - say numbMax:
|
unsigned long numbMax = std::numeric_limits<unsigned long>::max();
|
Next i fixed to get the value trough the users command line input using string stream converting it to the input integer and check if it is truly an integer - let's call this integer numb1. And now i want to examine if it doesn't exceed the systems limit. But i have a problem, before comparing it i will have to give numb1 a value and it might get out of bounds while doing so.
Is there a smart solution instead of checking the length of the string and each character?
Streaming the input to declared integer is done by:
1 2
|
inputNumber(&numb1, &numbMax);
std::cout << numb1 << std::endl;
|
And the user input function is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void inputNumber(unsigned long * numb, const unsigned long * numMax)
{
std::string bufStr;
bool tmpBool = true;
do
{
if (tmpBool) std::cout << "Enter the number smaller than " << *numMax << ": \n";
else std::cout << "Oops, wrong input. Try again... " << ": \n";
getline(std::cin, bufStr);
tmpBool = false;
}
while(!checkIntInput(bufStr));
std::stringstream(bufStr) >> *numb; //can cope trailing 0
}
|
To keep the set complete i give the function checkIntInput:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
bool checkIntInput(std::string & checkInt)
{
bool rtrn = true; // return value
if(checkInt.size() != 0)
{
char charInt;
int intChar;
for(std::size_t i = 0; i < checkInt.size(); ++i)
{
charInt = checkInt[i];
intChar = int(charInt) - 48;
//could add a break below, mhwa
if((intChar + 1) > 0 && (intChar < 10)) rtrn = false;
}
}
else rtrn = false;
|
Now passing the test the input will be string streamed to the actual integer (with its limits) and it should be compared with the integers limit - else: no go. But before this it can happen that the string stream represents a number to big to oblige the limit? And how should i make the program to participate in that? Again: without checking the characters in the input stream one by one.
Thank you for your help! Peter