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.