0

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;
 
}
  • Your `n`in an `int`. Then you can read integers only, even if you input a floating point number – Damien Dec 16 '20 at 10:47
  • Hi Damien, Thanks for responding. Im not sure I get what you mean. In my code if I for e.g. enter 2.5 the output is "you entered 2". I am looking for someway for the output to say "You entered an floating point, please enter a whole number" if that makes sense and is possible? – Chris Cassar Dec 16 '20 at 10:55
  • Then a possibility is to read a floating point number, cast it to an int, and check if both are equal or not. If you try to read `n`, as it is an integer, then you always get an integer ... – Damien Dec 16 '20 at 11:00

0 Answers0