Hello, I am very new to C++ and in the process of trying to write a programme. Part of the programme will be to work out a factorial amount which I have working, however I want the user to have to enter a whole number (not 0, negative or floating point) For simplicity I have written a basic example but I can not figure out how to write a "If entry = float, then error message. Am i missing something? unfortunately I have been trying to learn via google and youtube. Any help would be appreciated, even if its a "You need to google X,Y,Z" Thanks in advance
#include <iostream>
usingnamespace std;
int main()
{
int n {};
cout << "Please enter a number: ";
if (!(cin >> n) || (cin.peek() != '\n' && cin.peek() != '.'))
cout << "You have not entered a number\n";
elseif (cin.peek() == '.')
cout << "You have entered a float number\n";
elseif (n == 0)
cout << "You entered 0\n";
elseif (n < 0)
cout << "You have entered a negative number\n";
else
cout << "You entered: " << n << '\n';
}
However, if you only want to determine if the entered number is valid or not, then consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
int n {};
cout << "Please enter a number: ";
if (!(cin >> n) || cin.peek() != '\n' || n <= 0)
cout << "You have not entered a valid number\n";
else
cout << "You entered: " << n << '\n';
}
#include <iostream>
#include <string>
#include <limits>
usingnamespace std;
int main()
{
int n;
do {
cout << "Enter a number greater than 0. ";
cin >> n;
if(!cin) {
cout << "Not valid." <<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
n = 0;
}
} while(n <= 0);
return 0;
}
It should also be noted that you need not worry about anyone putting in a float value. It will be converted to an int automatically. If someone puts 5.8 for example it will take only the value of 5.