0

I have this simple code where I input values to two float variables and they get displayed. What I am not able to understand is what happens if I give my input as non numeric. Like when I input 'a'( without ' '), a strange number gets generated- 2.69525+0323.21398e=039. How and why is this number generated?

#include<iostream.h>

int main()
{
    float x,y;
    cin>>x>>y;
    cout<<x<<y;
    return 0;
}

Also, how can I stop someone from entering a non-numeric value? I thought of storing the number in an array,iterating through it and using isdigit(), also a case for seeing if a decimal point appears and it should only appear once but this seems a not so good approach. Any better approach?

3
  • The input fails, which you would know if you checked the return value, and the variables are left with whatever random uninitialized value they had when you declared them. Commented Aug 1, 2014 at 21:04
  • That is the random values x and y are initialized with. That's why you should always initialize your variables. Commented Aug 1, 2014 at 21:07
  • @RetiredNinja I don't know if it's a really stupid question but how do I check the value returned by main() ? Commented Aug 1, 2014 at 21:32

1 Answer 1

4

- 2.69525+0323.21398e=039 is actuall two strange numbers without a space between them.

They are most likely the random values that were in x & y to start with. The cin failed, so they were unchanged.

How can I stop someone from entering a non-numeric value?

  • Yell at them and threaten no dessert. - or -
  • import the values as strings, verfiy them as numbers, and then convert them to floats.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. So I get the value entered in a char array, verify them as number using isdigit()? But what should I do of the decimal point in between? Please elaborate the procedure a little. I am not very sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.