First of all you should forget that there is the goto
statement in C.
All programs that contained a goto
statement and I saw including some IBM's source code had numerous bugs related to goto
statements.
The goto
statement makes programs difficult to read and more difficult to maintain and modify them.
Using the goto
statement is the same as traffic violatins.:)
Instead of this code snippet
start:
printf("[c] Converts Celsius -> Fahrenheit\n[f] Converts Fahrenheit -> Celsius\n\n\n");
printf("Enter Choice: ");
scanf("%c",&choice);
if (choice!='c' || choice!='f' || choice!='x') {
printf("Wrong Choice: Try Again!");
goto start;
}
that at least has an invalid condition in the if statement
if (choice!='c' || choice!='f' || choice!='x')
instead of valid
if (choice!='c' && choice!='f' && choice!='x')
You could write for example
enum { Celsius = 'c', Fahrenheit = 'f', Exit = 'x' };
char choice;
int valid_input;
do
{
printf( "[c] Converts Celsius -> Fahrenheit\n"
"[f] Converts Fahrenheit -> Celsius\n"
"[x] Exit\n\n" );
printf( "Enter Choice: " );
if ( scanf( "%c ", &choice ) != 1 ) choice = Exit;
valid_input = choice == Celsius || choice == Fahrenheit || choice == Exit;
if ( !valid_input ) puts( "Wrong Choice: Try Again!\n" );
} while ( !valid_input );
Your program contains numerous bugs. Insetad of to list them I will show how
the program could be written
#include <stdio.h>
int main( void )
{
enum { Celsius = 'c', Fahrenheit = 'f', Exit = 'x' };
char choice;
int valid_input;
do
{
printf( "[c] Converts Celsius -> Fahrenheit\n"
"[f] Converts Fahrenheit -> Celsius\n"
"[x] Exit\n\n" );
printf( "Enter Choice: " );
if ( scanf( "%c ", &choice ) != 1 ) choice = Exit;
valid_input = choice == Celsius || choice == Fahrenheit || choice == Exit;
if ( !valid_input ) puts( "Wrong Choice: Try Again!\n" );
} while ( !valid_input );
switch( choice )
{
float x, y;
case Celsius: case Fahrenheit:
printf( "Input Value: " );
if ( scanf( "%f", &x ) == 1 )
{
if ( choice == Celsius )
y = 1.8 * x + 32;
else
y = ( x - 32 ) * ( 5.0f / 9.0f );
printf( "Result: %.2f\n", y );
}
case Exit:
puts( "Bye!" );
break;
}
return 0;
}
if to enter sequentially
c 20 x
then the output will look like
[c] Converts Celsius -> Fahrenheit
[f] Converts Fahrenheit -> Celsius
[x] Exit
Enter Choice: c
Input Value: 20
Result: 68.00
Bye!