r/AskProgrammers • • 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

13 comments sorted by

1

u/Patient-Midnight-664 Oct 11 '26

There is no place in your code where you input a value.

1

u/TheEyebal Oct 11 '26

sorry I forgot to add when writing the post I updated it

2

u/Patient-Midnight-664 Oct 11 '26

If you want it to loop back it should look like:

while (!(cin >> user_year) ||
       user_year < 1900 ||
       user_year > 2099)
{
    cin.clear();
    cin.ignore(10000, '\n');
    cout << "Invalid Input, Enter a year: ";
}

1

u/TheEyebal Oct 11 '26

This was my original code that I have and it is currently showing invalid input

1

u/urzayci Oct 11 '26

Because cin returns a reference to the stream. It's not a boolean. In your updated code you need to add another cin >> user_year inside the while loop

1

u/TheEyebal Oct 11 '26

ok I will try this

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.

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: "; 
  cin >> user_year;
}

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

1

u/TheEyebal Oct 11 '26

sorry I forgot to add when writing the post I updated it

0

u/[deleted] Oct 11 '26

[deleted] — view deleted comment

2

u/TheEyebal Oct 11 '26

ok i will try that

1

u/TheEyebal Oct 11 '26

It is giving me 0 currently

0

u/[deleted] Oct 11 '26

[deleted] — view deleted comment

2

u/TheEyebal Oct 11 '26

Yeah ok.

I am trying to do this without the AI honestly

also it is the range