Problem with C++ understanding chars within float input

#include <iomanip>
#include <math.h>

int main() {

    float x, a, b;
    char conditions[] = { 'Y', 'y' };

    std::cout << "Enter a number: ";
    std::cin >> x;

    if (!std::cin) {
        std::cout << "error";
    }
    else {
        a = x * x;
        std::cout << "A is: " << a << std::endl;
    }

}
//I need to create an if statement or a loop to
//ask to input float x again if char conditions were input instead.

I have a problem I've been trying to find an answer to for weeks. From the code you can see that !std::cin condition won't accept any chars, therefore an error will be printed. I however need an exception where if 'y' || 'Y' is inputted it loops back to the std::cin >> x; and asks for a float value again until it is provided, however if any other char is inputted like 'h' it would obviously go back to the error message.

I've tried multiple if statements, checked recursives but no luck. The problem is that I can't make the exceptions because if 'y' is inputted then the program doesn't understand it because the std::cin >> is asking for a number not a char...



from Recent Questions - Stack Overflow https://ift.tt/2Y3AgLe
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation