Hi, I'm new to both c++ and programming. Can someone explain why my program works for all integers, but not when I input a letter? What is actually happening when I declare an int, but input a non-int? Thanks
Also, I see that I can input a float and it will accept it (outputs "Thanks"). I see that if converts the float 6.5 into 6 (when I cout << n). Is it normal to round down when converting float to an int?
#include <iostream>
usingnamespace std;
// Identify if an input is within bounds.
int main()
{
int n;
int i;
cout << "Please type a positive integer between 0 and 1,000,000: ";
cin >> n;
for(i = 0; i < 4; i++) // User has 5 tries to provide adequate input
{
if(n > 0 && n <= 999999) // Create bounds for input
{
// Accept number if within boundaries
cout << "Thanks";
return 0;
}
else
{
cout << "This value is not valid, please try again: ";
cin >> n;
// If input is not within bounds, ask user to try again
//return 0 after 5 tries
}
}
return 0;
}
Okay, thanks! That makes sense. Right now my goal is to find a way to allow the user give input again even if the initial input is a non-integer. Is this possible?