mercredi 16 décembre 2020

C++ code - Error message when floating point is entered [duplicate]

I think this will be a simple question for anyone with knowledge of C++. I am new to C++ (please be gentle). I am trying to write a bit of code that asks the user to enter a whole number greater than 0. If they enter 0, they get an error message, if they enter a negative number they get an error and when they enter a floating point, they get an error. The code I have seems to do all except the floating point. Can someone please help?

#include <iostream>
#include <string>

using namespace std;

int main()
{
 int n;
 
 cout <<"Please enter a number:  " << endl;
 cin >> n ; 
 
 if(n == 0)
 
 {
 cout << "You entered 0, please enter a whole number greater than 0" << endl; 
 }
 
 if(n < 0) {
     
     cout <<"You have entered a negative number" << endl;
     
 }
 
 else {
     
     cout <<"you entered: " << n << endl;
     
 }
 return 0;
 
}

Aucun commentaire:

Enregistrer un commentaire