0

I made a program based on function overloading consisting of 2 functions int cube (int) and float cube(float) . My main function reads values of int x and float y respectively.Now when I run the program I put a float value instead the integer va;ue And when I put 2.5(decimal value) instead of integer value in variable "x" , The compiler does not ask me the value of y and automatically 2 for x (int) and 0.5 for y (float) and returns the cube of 0.5. Why this is happenning. Why 0.5 is automatically stored in y instead of asking input?

My program is like that -

#include<iostream>
using namespace std;
int main()
{
    int x;
    float y;
    int cube(int);
    float cube(float);
    cout<<"Enter a number to find its cube"<<endl;
    cin>>x;
    cout<<"The cube of the number "<<x<<" is "<<cube(x)<<endl;

    cout<<"Enter a number to find its cube"<<endl;
    cin>>y;
    cout<<"The cube of the number "<<y<<" is "<<cube(y)<<endl;
    return 0;
}
int cube (int num)
{
    return num*num*num;
}

float cube (float num)
{
    return num*num*num;
}

Output is -

Enter a number to find its cube
2.5
The cube of number 2 is 8
Enter the number to find its cube
The cube of number 0.5 is 0.125

Can anyone help me about that Thanks

2
  • I suggest using a template method Commented May 27, 2017 at 13:35
  • The question title does not really give any clue about the problem. This problem must be reasonably common among beginners, but I couldn't find a dupe with a quick search. Commented May 27, 2017 at 13:45

2 Answers 2

1

You try to read an int value, but give a floating point value as input. That means the program will read the integer part, stop reading as soon as it sees something that doesn't match the pattern of an integer value (the '.' in your case) and leave it in the input buffer for the next input operation.

If you want to read whole lines and discard unparsed input, then either use std::istream::ignore after each input. Or read a whole line into a string using std::getline and use an std::istringstream to "parse" the input.

Sign up to request clarification or add additional context in comments.

Comments

0

This is quite simple:

cout<<"Enter a number to find its cube"<<endl;

you enter 2.5

cin>>x;

this reads 2 (sets x=2) and stops, because the .5 cannot be part of an int.

cout<<"The cube of the number "<<x<<" is "<<cube(x)<<endl;

cout<<"Enter a number to find its cube"<<endl;
cin>>y;

the .5 is still in the input stream, so is read to set y=0.5. There is no need to enter another number, and so the program does not stop to wait for input.

Comments

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.