B
bildad
The following 'book example' of validating input seems to be incomplete.
Since it is a beginner's book it may be intentional for simplicity. But
I would like to know how to make this program work for all invalid
input. Just for example, if user inputs 'abc' an error is caught, but if
user inputs '432' the program hangs. Any clarification appreciated.
Thanks,
Bill
#include <stdio.h>
int main(void)
{
float temp_i, temp_o;
char which_i, which_o;
char junk;
printf("Enter a temperature and indicate\n");
printf("if it's Fahrenheit or Celsius [##.# C/F]: ");
if (scanf("%f %c", &temp_i, which_i) == 2)
{
switch (which_i)
{
case 'C':
case 'c':
temp_o = (temp_i * (9.0/5.0)) + 32;
which_o = 'F';
break;
case 'F':
case 'f':
temp_o = (temp_i - 32) * (5.0/9.0);
which_o = 'C';
break;
default:
which_o = 0;
break;
}
if (which_o)
{
printf("%0.1f %c is %0.1f %c.\n",
temp_i, which_i, temp_o, which_o);
}
else
{
printf("You failed to enter C or F.\n");
}
}
else
{
printf("You failed to use the proper syntax.\n");
}
do {
junk = getchar();
} while (junk != '\n');
getchar();
return 0;
}
Since it is a beginner's book it may be intentional for simplicity. But
I would like to know how to make this program work for all invalid
input. Just for example, if user inputs 'abc' an error is caught, but if
user inputs '432' the program hangs. Any clarification appreciated.
Thanks,
Bill
#include <stdio.h>
int main(void)
{
float temp_i, temp_o;
char which_i, which_o;
char junk;
printf("Enter a temperature and indicate\n");
printf("if it's Fahrenheit or Celsius [##.# C/F]: ");
if (scanf("%f %c", &temp_i, which_i) == 2)
{
switch (which_i)
{
case 'C':
case 'c':
temp_o = (temp_i * (9.0/5.0)) + 32;
which_o = 'F';
break;
case 'F':
case 'f':
temp_o = (temp_i - 32) * (5.0/9.0);
which_o = 'C';
break;
default:
which_o = 0;
break;
}
if (which_o)
{
printf("%0.1f %c is %0.1f %c.\n",
temp_i, which_i, temp_o, which_o);
}
else
{
printf("You failed to enter C or F.\n");
}
}
else
{
printf("You failed to use the proper syntax.\n");
}
do {
junk = getchar();
} while (junk != '\n');
getchar();
return 0;
}