Hi guys.
For some unknown reason, my code is not working. It works during the first switch, but after scanning for the first input, the program terminates unexpectedly.
Can you give some feedback about what is wrong with it?
Thanks in advanced.
Code:
/*
Write a program in “BASES.C” which offers the user a choice of converting integers between
octal, decimal and hexadecimal. Prompt the user for either ‘o’, ‘d’ or ‘h’ and read the number
in the chosen format. Then prompt the user for the output format (again ‘o’, ‘d’ or ‘h’) and print
the number out accordingly.
A nice enhancement would be to offer the user only the different output formats, i.e. if ‘o’ is
chosen and an octal number read, the user is offered only ‘d’ and ‘h’ as output format.
*/
#include <stdio.h>
void main ()
{
int number;
char option1, option2;
printf("Choose an input number format:\n");
printf("\td - decimal\n\to - octal\n\th - hexadecimal\n");
scanf("%c", &option1);
switch (option1)
{
case 'd':
printf ("Enter the a number in the chosen format:\n");
scanf ("%d", &number);
printf ("Choose an output number format:\n");
printf ("\to - octal\n\th - hexadecimal\n");
scanf ("%c", &option2);
switch (option2)
{
case 'o':
printf("The decimal number %d in octal base is: %o\n", number, number);
break;
case 'h':
printf("The decimal number %d in hexadecimal base is: %x\n", number, number);
break;
default:
printf ("Unknown option chosen.\n");
break;
}
break;
case 'o':
printf ("Enter the a number in the chosen format:\n");
scanf ("%o", &number);
printf("Choose an output number format:\n");
printf("\td - decimal\n\th - hexadecimal\n");
scanf("%c", &option2);
switch (option2)
{
case 'd':
printf("The octal number %o in decimal base is: %d\n", number, number);
break;
case 'h':
printf("The octal number %o in hexadecimal base is: %x\n", number, number);
break;
default:
printf ("Unknown option chosen.\n");
break;
}
break;
case 'h':
printf ("Enter the a number in the chosen format:\n");
scanf ("%x", &number);
printf("Choose an output number format:\n");
printf("\to - octal\n\td - decimal\n");
scanf("%c", &option2);
switch (option2)
{
case 'o':
printf("The hexadecimal number %x in octal base is: %o\n", number, number);
break;
case 'd':
printf("The hexadecimal number %x in decimal base is: %d\n", number, number);
break;
default:
printf ("Unknown option chosen.\n");
break;
}
break;
default:
printf ("Unknown option chosen.\n");
break;
}
// getchar ();
}