Spróbuj wczytywanie do zmiennej przenieść do osobnej funkcji, co znacznie uprości program.
#include <iostream>
#include <limits>
using namespace std;
int getValue()
{
int value;
while(!(cin >> value))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Bledne dane wejsciowe! Wpisz liczbe: ";
}
return value;
}
int main()
{
for(;;)
{
cout << "Podaj numer miesiaca a zwroce ile ma dni" << endl;
auto nr_miesiaca = getValue();
switch( nr_miesiaca )
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
cout << "ten miesiac ma 31 dni!" << endl << endl;
break;
case 4: case 6: case 9: case 11:
cout << "ten miesiac ma 30 dni!" << endl << endl;
break;
case 2:
int rok;
cout << "Podaj rok: ";
rok = getValue();
if( ((rok%4==0)&&(rok%100!=0)) || (rok%400==0) ) cout << "ten miesiac ma 29dni" << endl << endl;
else cout << "ten miesiac ma 28dni" << endl << endl;
break;
default: cout << "Niepoprawny numer miesiaca" << endl << endl; break;
}
}
return 0;
}
Możesz też w ogóle zrezygnować z funkcji switch i skorzystać z trochę bardziej zaawansowanego kodu:
#include <iostream>
#include <limits>
#include <map>
using namespace std;
int getValue()
{
int value;
while(!(cin >> value))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Error input data! Try again: ";
}
return value;
}
map<int,int> days = { {1,31},{3,31},{4,30},{5,31},{6,30},{7,31},{8,31},{9,30},{10,31},{11,30},{12,31} };
int main()
{
auto daysInFebruary = []( int year ){ return ((year%4==0)&&(year%100!=0))||(year%400==0) ? 29:28; };
auto month {1};
while( month!=0 )
{
cout << "Give number of month [1-12] or 0 to end:" << endl;
month = getValue();
if( month>0 && month<13 )
{
if( month == 2 )
{
cout << "Give year for February: ";
days[2] = daysInFebruary(getValue());
}
cout << "The month has " << days[month] << " days!" << endl << endl;
}
else if( month!=0 ) cout << "Improper number of month!" << endl << endl;
}
return 0;
}