Inputting non-int into int variable

Dec 27, 2017 at 8:22pm
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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace 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;
}
Last edited on Dec 27, 2017 at 8:29pm
Dec 27, 2017 at 8:40pm
What is actually happening when I declare an int, but input a non-int?

The stream enters an error state because it can't convert the input into a number.

I see that if converts the float 6.5 into 6 (when I cout << n).

Actually the stream stops processing the input when it encounters a non-digit, leaving the remaining characters in the input buffer.

Is it normal to round down when converting float to an int?

It is not rounding down, it is just processing integer values, remember an integer has no fractional parts.

Dec 27, 2017 at 8:45pm
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?
Dec 27, 2017 at 8:48pm
Fetch input as a string.

Then examine the input to check if it's acceptable to you. If it is, do what you want with it (e.g. turn into an int, store that int).

If not acceptable, tell the user to go again.
Dec 27, 2017 at 8:59pm
Thanks again. I will try this out.
Topic archived. No new replies allowed.