1

I wanted to make a "leap year" programm as practice.
This is my code:

#include <iostream>
#include <string>

int main (){
int year;
std::string flag01;
do {
    std::cout << "Input year: ";
    std::cin >> year;
//check for int input
    while (std::cin.fail()){
        std::cout << "Oops..." << std::endl << "I failed to get a year..." << std::endl << "Try again?";
        std::cin.clear();
        std::cin >> year;
    }
    if (year % 4 == 0 && year % 100 != 0 && year != 0)
        std::cout << "the year " << year << " is a leap year.\n";
    else
        std::cout << "the year " << year << " is not a leap year.\n";
    std::cout << "Would you like to input another?  yes / no \n";
    do {
        std::cin >> flag01;
            if (flag01 != "yes" && flag01 != "no")
                std::cout << "please only insert yes or no\n";
    } while (flag01 != "no" && flag01 != "yes");
} while (flag01 != "no");
return 0;
}

But I can't make the part where it checks if what you input is an int or not, work. I don't know what I am doing wrong.
When I run it and input a char or string it goes in an infinite loop and keeps printing the line 11.

I saw the std::cin.fail and std::cin.clear here: Checking input value is an integer

Please help and thanks.

Community
  • 1
  • 1
axxooss
  • 13
  • 3

1 Answers1

0

You are clearing the error state, but the data that caused the error is still in the stream. Clear it with ignore...

    std::cout << "Oops..." << std::endl << "I failed to get a year..." << std::endl << "Try again?";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //extract all characters until /n
    std::cin >> year;

Include header limits for std::numeric_limits.

#include <limits>
Unimportant
  • 2,076
  • 14
  • 19
  • Now it works so thanks! Just another question; `numeric_limits` and `streamsize` "are in `std`", but is `max()` also the same?. If the answer is too big, where can I read up on it? – axxooss Oct 26 '15 at 07:20
  • `max()` is a member function of `std::numeric_limits` which returns the maximum value for the given template type `std::streamsize`. By using the maximum streamsize it is guaranteed that the entire stream is cleared. – Unimportant Oct 26 '15 at 10:21
  • I get it now. Thanks again! – axxooss Oct 26 '15 at 13:58