Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't compare types of variables in C++

I have following function within a class, which gets real part of a complex number:

double inputReal(){
        double real;
        cout << "Enter real part: ";
        cin >> real;
        bool compare = typeid(real) == typeid(double);
        while (compare != true){
            cout << "Incorrect input. Try another input: ";
            cin >> real;
        }
        return real;
    }

It should check if real is actually a number and if real isn’t a number – it should get another input. However, if I try inputing something like: "aa" or "#@", it skips the while part and proceeds to output, ignoring getting the imaginary part:

double inputImag(){
        double imaginary;
        cout << "Enter imaginary part: ";
        cin >> imaginary;
        bool compare = typeid(imaginary) == typeid(double);
        while (compare != true){
            cout << "Incorrect input. Try another input: ";
            cin >> imaginary;
        }
        return imaginary;
    }

Output, if I try inputing "aa" as a real part:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter real part: aa
Enter imaginary part: Absolute value of complex number: 0
Argument of complex value: 0
Program ended with exit code: 0

The code works just fine, if I input correctly, so I suspect it’s the comparison of types within those functions. I need to know what did I do wrong and how I can fix it. I’m relatively new to C++ and my college professor requires checking, that user inputs correctly. Feel free to ask anything, if the question seems unclear.

>Solution :

typeid(real) == typeid(double) will always be true since real is a double.

If you want to check that you have valid input, you need to actually check the input. Here is one way of doing that

double inputReal()
{
    std::size_t end_pos{};
    std::string input;
    std::cout << "Enter real part: ";
    while (getline(std::cin, input))              // get the full line of input
    {
        double real = std::stod(input, &end_pos); // convert to double 
        if (end_pos == input.size())              // check to see if all of the input was converted
            return real;
        else
            std::cout << "Incorrect input. Try another input: ";
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading