3
Good Morning,
I wanted to know how I can optimize the cleaning of the buffer when using the getchar() function, as an example follow the following codes:
I get the following code to have the correct output using the "scanf spacing as I demonstrate:
#include <stdio.h>
int main()
{
float salario, imposto = 0.0;
char sexo;
printf ("Introduza o Salário: ");
scanf("%f",&salario);
printf ("Introduza o sexo: ");
scanf (" %c",&sexo);
switch (sexo)
{
case 'f':
case 'F': imposto = 0.10;
break;
case 'm':
case 'M': imposto = 0.05;
break;
}
printf("Imposto %.2f\n",salario*imposto);
return 0;
}
However I cannot correctly execute the following code:
#include <stdio.h>
int main()
{
float salario, imposto = 0.0;
char sexo;
printf ("Introduza o Salário: ");
scanf("%f",&salario);
printf ("Introduza o sexo: ");
sexo = getchar();
switch (sexo)
{
case 'f':
case 'F': imposto = 0.10;
break;
case 'm':
case 'M': imposto = 0.05;
break;
}
printf("Imposto %.2f\n",salario*imposto);
return 0;
}
Introducing the following Output without letting me enter sex:
Enter Salary: 100 Enter Gender: Tax 0.00
Thanks for the help.
Out of curiosity What would happen if we used getchar() if the buffer was empty.
– axell-brendow
The code would stop, waiting for a keyboard input.
– mutlei
Our Is Really, I Knew It And Flying, I Use Direct getchar() To Pause asuashsuahusa
– axell-brendow