Hello all i was wondering could someone help me , on the ELSE what im triying to do is to ask me again the correct number which will be 1 trough 7 and "forcing" the user to input the numbers of 1 trough 7.
#include <stdio.h>
#include <conio.h>
int main()
{
int dia;
printf("Escriba el número de día: \n");
scanf("%d",&dia);
if(dia>=1 && dia<=8)
switch(dia)
{
case 1: printf("El día es Lunes");
break;
case 2: printf("El día %d es Martes",dia);
break;
case 3: printf("El día %d es Miércoles",dia);
break;
case 4: printf("El día %d es Jueves",dia);
break;
case 5: printf("El día %d es Viernes",dia);
break;
case 6: printf("El día %d es Sábado",dia);
break;
case 7: printf("El día %d es Domingo",dia);
break;
}
else {
printf("ingrese número del 1-7");
}
getch();
return 0;
}
CodePudding user response:
This is called default
for instance:
switch(c){
case 0:
printf("c is zero\n");
break;
case 1:
printf("c is one\n");
break;
case 2:
printf("c is two\n");
break;
default:
printf("c is not zero one or two\n");
break;
}
CodePudding user response:
A way to do what you want to achieve is to keep the user in a loop until they enter the correct input. Like:
#include <stdio.h>
#include <conio.h>
int main()
{
int dia;
do{
printf("Escriba el número de día: \n");
scanf(" %d",&dia);
if(dia<1||dia>8)
printf("ingrese número del 1-7");
}while(dia<1||dia>8);
if(dia>=1 && dia<=8)
switch(dia)
{
case 1: printf("El día es Lunes");
break;
case 2: printf("El día %d es Martes",dia);
break;
case 3: printf("El día %d es Miércoles",dia);
break;
case 4: printf("El día %d es Jueves",dia);
break;
case 5: printf("El día %d es Viernes",dia);
break;
case 6: printf("El día %d es Sábado",dia);
break;
case 7: printf("El día %d es Domingo",dia);
break;
}
getch();
return 0;
}
CodePudding user response:
You can achieve your objective with far less code...
#include <stdio.h>
int main() {
int dia = 0; // ALWAYS initialise variables
char *str = NULL;
printf( "Escriba el número de día: " );
while( str == NULL ) {
scanf( "%d", &dia );
/* omitting test for failure */
switch( dia ) {
case 1: str = "Lunes"; break;
case 2: str = "Martes"; break;
case 3: str = "Miércoles"; break;
case 4: str = "Jueves"; break;
case 5: str = "Viernes"; break;
case 6: str = "Sábado"; break;
case 7: str = "Domingo"; break;
// Catch any invalid input leaving str == NULL
default:
printf( "ingrese número del 1-7: " );
break;
}
}
printf( "El día %d es %s\n", dia, str );
getch();
return 0;
}
When the user enters a valid number, the pointer 'str' changes from NULL to the address of a weekday name. This causes the loop to exit, and the day number and name are printed.