The main reason why, when an end user enters a floating point number where an integer is required, the program not only takes the integer into account, but also assigns the stored floating points of the previously entered number to the next variable, is the buffer - which is essentially a temporary storage of data that is moved to another memory or data storage.
To fix this, you need to use the cin.ignore()
function, which is a great function used to ignore and/or clear one or more characters from the input buffer.
If, for example, you add a std::cin. ignore(100,'\n')
, it would clear the buffer to allow the program to read and consider the next condition or statement. The number 100
in the syntax
is just there to ignore a specific number of characters (100 characters) before the specified boundary, in this case the newline character '\n'
, but it can, of course, be any number - depending on the number of characters you have.
Also, note that in your outputs
(cout<<"The input number is x= "<<endl;)
and
(cout<<"The float number is y= "<<endl;)
you did not make reference to the x and y variables, hence you may not get the expected results, as the program will not output the values stored in these variables.
So, take a look at my approach, below:
#include<iostream>
using namespace std;
int main()
{
int x;
float y;
cout<<"Please input an integer:"<<endl;
cin>>x;
cout<<"The entered integer is: "<<x<<endl;
std::cin.ignore(100, '\n');
cout<<"Please input a floating point number: "<<endl;
cin>>y;
cout<<"The entered float number is: "<<y<<endl;
return 0;
}