How we can Validate the Float number in c++?

SDKING

SDKING

@sdking-03Di1M • Oct 21, 2024

I have to input only float number..
bcoz..i want to devlop the program for addition of two float numbers.In that if user gave integer numbers then the i want to generate exception....hence i having problem with checking the user input whether it is float numbers or integers....I want to perform addition with only an only with float numbers....Any one tell me to how the float value is validate....help me...👎

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Vishal Sharma

    Vishal Sharma

    @vishal-pysGmK Apr 1, 2013

    there's no need of generating an exception..
    Every integer arithmetic's can be performed using float too...
    so your program will work fine!

  • rahul69

    rahul69

    @rahul69-97fAOs Apr 1, 2013

    As Vishal0203 said there is no need for exception, because there is no purpose of excluding the integers in that manner,
    However if u still want to try it, here is one method:
    Suppose the floating point no is stored in fno

    • Create an integer no (ie int no😉
    • Copy fno to no
    • Subtract fno from no, if result is zero, then throw exception ( as it would be integer )

    Good Luck!

  • SDKING

    SDKING

    @sdking-03Di1M Apr 1, 2013

    @vishal0203- i think you could not understand my problem.
    my problem is the addition of floating point numbers so i want only addition of float number like..
    float a=12.30,b=34.55;
    float c=a+b;
    and if in this user gave integer input so in that time no need to add that numbers.
    boz i want only float numbers..
    Hence i want to create code for accepting float number only....👎

  • SDKING

    SDKING

    @sdking-03Di1M Apr 2, 2013

    @rahul69-thnx for previous help...your guidance is much helpful for me....

  • Ankita Katdare

    Ankita Katdare

    @abrakadabra Apr 6, 2013

    #-Link-Snipped-# In C++, if you want to detect that the input value is valid or invalid, so what you can do is first accept your input as strings, validate those strings, then if valid, only then convert the strings to float numbers using the atof() function.

    For example:

    string num1, num2;
     
        cin >> num1;
        if( num1.find_first_not_of("1234567890.-") != string::npos )
        {
            cout << "invalid number: " << num1 << endl;
            return;
        }

    Or just do this, if it suits your requirement:

    float x, y;
    if (std::cin >> x >> y) {
        // Do whatever you want
    }
    else {
        // Say it is invalid
    }
  • SDKING

    SDKING

    @sdking-03Di1M Apr 7, 2013

    Absolutly ri8.....This is Work....thnx AbraKaDabra..