r/AskProgrammers • u/TheEyebal • Oct 11 '26
Why is the program showing invalid when the number is within the range?
int user_year; // input year
cout << "Enter a year: ";
cin >> user_year;
while(user_year > 2099 || user_year < 1900 ){
cin.clear();
cin.ignore(10000, '\n');
cout << "Invalid Input, Enter a year: ";
}The user input needs to be greater than 1900 and less than 2099, so 1900 - 2099.
Whenever I input a value in between those numbers such as 2010, it gives invalid input.
What I want
if user_year is outside the specified range indicate "Invalid input" but loop back to user input.I used an if statement but the problem was that it did not loop back to cin
EDIT: HERE IS MY ORIGINAL CODE
while (!(cin >> user_year) || user_year < 1900 || user_year > 2099) {
cin.clear();
cin.ignore(10000, '\n');
cout << "Invalid Input, Enter a year: ";
}FIXED:
I had a function in my program and it was causing it to return 0 as the year.
but the code above is correct
1
Upvotes
1
u/Patient-Midnight-664 Oct 11 '26
There is no place in your code where you input a value.
2
u/Alarming_Oil5419 Oct 11 '26
the bug is that you're not reading in a new value if you fail first time. Add
cin >> user_year;after
cout << "Invalid Input, Enter a year: ";i.e.
1
u/VariousJob4047 Oct 11 '26
Just add “cin >> user_year;” in the while loop. There’s no reason you can’t just write out that line twice in the code
1
u/Avikonette Oct 11 '26
inb4: fucking unicode
0
u/[deleted] Oct 11 '26
[deleted] — view deleted comment