I am creating a simple area calculator that exhibit overloading. I already finished the overloading function, my concern is, I want to key trap the pressed letters/characters by the user. I want to allow only numbers (int & float data type) input. How will I do that? Thanks. I am using Dev C++.

Here is some part of my code:

if (yourchoice ==1){
        cout << "\n---- Area of Square ----";
             cout <<"\nSide of Square: ";
             cin >> SqSide;

            int AreaSquare=area(SqSide);
            cout<<"\n Area of a Square is = "<<AreaSquare << endl;

    }else if (yourchoice ==2){
             cout << "\n---- Area of Rectangle ----\n";
             cout <<"Length of the Rectangle: "; 
             cin >> length;

             cout <<"\nWidth of the Width: ";
             cin >> width;


          int AreaRectangle=area(length, width);
          cout<<"\n Area of Rectangle is = "<<AreaRectangle << endl;

When the user cin a letter/character, I want the program to prompt that the user inputted a wrong input. If the user cin a number/numbers, the program will proceed to the function and calculate the area.

Recommended Answers

All 3 Replies

you need to include ctype header.
then once you recieve the input you check with isdegit() method.
its a bool method so you do if statement.

I want to allow only numbers (int & float data type) input. How will I do that?

The usual and recommended approach is to simply allow the user to type anything and then throw errors if it doesn't match what you're expecting. For example with numbers only:

#include <ios>
#include <iostream>
#include <limits>

using namespace std;

int main()
{
    double num;

    while (true) {
        cout << "Enter a number: ";

        if (cin >> num) {
            break;
        }
        else {
            cout << "Invalid input. Please try again\n";

            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }

    cout << "The square of " << num << " is " << num * num << '\n';
}

This takes advantage of the fact that cin's operator>> will perform formatting and error checking on the input string based on the type of the target variable. In this case, operator>> will try to ensure that the input string is a valid floating-point value.

In cases where the default validation doesn't fit your needs, you would read the input as a free-form string and then validate it yourself. However, that's not typically recommended for basic cases as it can get complex quite quickly.

Finally, some people want to restrict input at the keyboard level. For example, completely disabling the non-digit keys when they're typed. This isn't supported by C++ natively, so you would need to write a non-portable input function that takes over the job of the command shell:

#include <cctype>
#include <iostream>
#include <string>
#include <conio.h> // Some non-portable library for raw input

using namespace std;

string get_numeric()
{
    string result;
    int ch;

    while ((ch = getch()) != '\r') {
        if (ch == '\b') {
            // Handle a destructive backspace; remove from the string and the console
            result.pop_back();
            cout << "\b \b" << flush;
        }
        else if (isdigit(ch)) {
            char digit = static_cast<char>(ch);

            // Add the character to the string and the console
            result += digit;
            cout << digit << flush;
        }
    }

    return result;
}

int main()
{
    auto input = get_numeric();

    if (input.empty()) {
        cerr << "No input provided\n";
    }
    else {
        int num = stoi(get_numeric());

        cout << "The square of " << num << " is " << num * num << '\n';
    }
}

Alternatively you can adjust the settings of the command shell if that's supported on your operating system. However, these last two approaches are not recommended. If you need that kind of control then you're entering the realm of a GUI application and should consider that instead of a console application.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.