Error in the switch statement in C ++

1
#include<iostream>
#include<Stdlib.h>
using namespace std;
class fecha{
    private:
        int dia,mes,anyo;
    public:
        void asignarfecha();
        void obtenerfecha(int *a,int *b,int *c);
        int fechacorrecta();
};

void fecha::asignarfecha(){
        cout<<"***introduce fecha***"<<endl;
        cout<<"introduce dia"<<endl;
        cin>>dia;
        cout<<"introduce mes"<<endl;
        cin>>mes;
        cout<<"introduce anyo"<<endl;
        cin>>anyo;
        };
void fecha::obtenerfecha(int *a,int *b,int *c){
    *a=dia;
    *b=mes;
    *c=anyo;
};
int fecha::fechacorrecta(){
    if(mes>0 || mes<13){
    switch(mes){
        case 1,3,5,7,8,10,12:
            if(dia<1 || dia>31){
                cout<<"error dia"<<endl;
            }
            break;
        case 2:
            if(dia<1 || dia>28){
                cout<<"error dia"<<endl;
            }
            break;
        case 4,6,9,11:
            if(dia<1 || dia>31){
                cout<<"error dia"<<endl;
            }
            break;
            default:
                cout<<"opcion invalida"<<endl;
        }
    }
    }
    else{
        cout<<"Error"<<endl;
    }
};
main(){
    int x,y,z;
    class fecha f;
    f.asignarfecha();
    f.obtenerfecha(&x,&y,&z);
    cout<<x<<"/"<<y<<"/"<<z<<endl;
    f.fechacorrecta();
}
    
asked by Edwin Casco 04.05.2017 в 00:26
source

2 answers

2
case 1,3,5,7,8,10,12:
  if(dia<1 || dia>31){
    cout<<"error dia"<<endl;
  }
  break;

This instruction is not legal in C ++. You have to put each case separately:

case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
  if(dia<1 || dia>31){
    cout<<"error dia"<<endl;
  }
  break;

The separator for " cases " is found in the break statement:

case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
  // ...
  break;

case 2:
  // ...
  break;

case 4:
case 6:
case 9:
case 11:
  // ...
  break;
    
answered by 04.05.2017 в 00:32
0

It is possible that switch accepts characters, or converting them into integers that in turn mean a number within your cases, or simply using '' in cases.

char c ='a';

switch((int)c)
{
  case 97:
  {
   /* Code */
  } break;
}

Or in the most direct case:

char c = 'a';
switch(c)
{
  case 'a':
  {
   /* Code */
  } break;
}
    
answered by 04.05.2017 в 06:22