0

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.

Makst
  • 103
  • 3

1 Answers1

-1

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

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Sagar Maiyad Apr 19 '14 at 06:06
  • @Achilles The question was "How can I fix this?" The answer outlines the way to fix this. If you think it does that in insufficient detail, or is otherwise unclear, feel free to downvote or flag. – n. m. could be an AI Apr 19 '14 at 06:38
  • Modifying the input method to `cin >> unconverted_input; const char* converted_input = unconverted_input.c_str(); input_value = strtoll(converted_input, NULL, 10);` where unconverted_input is a c++ string, worked perfectly for me. – Makst Apr 19 '14 at 19:39
  • Don't forget to check `errno` after the conversion! – n. m. could be an AI Apr 19 '14 at 19:50