Question

I have a function in my C++ program that collects one number from the terminal.

I want it to accept any number input from the user, reduce numbers outside the signed long long int range to the exact limit, correctly inform the user of any reduction, and return successfully.

All non-number inputs should be completely thrown out and re-prompt the user infinitely.

I thought overly-huge inputs would be automatically reduced to the signed limit, but instead this function treats them as invalid and gives me the non-number re-prompt. How can I fix this?

void get_input(long long int& input_value)
{
    while(0==0) //infinite loop
    {
        cout << "Input whole number: ";
        if(cin >> input_value)
        {
            cout << endl;
            if (input_value >= LLONG_MAX)
            {
                cout << "Size limit exceeded. " << LLONG_MAX << " will be used instead.\n\n";
            }
            else if (input_value <= LLONG_MIN)
            {
                cout << "Size limit exceeded. " << LLONG_MIN << " will be used instead.\n\n";
            }
            cin.clear();
            return;
        }
        else
        {
            cout << "Please input a numeral.\n\n"; //trash invalid input
            string garbage;
            cin.clear();
            getline(cin,garbage);
        }
    }
}

I am including iostream, string, and climits, and globally using namespace std.

Was it helpful?

Solution

You want to input a string and use strtoll on it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top