You're using the assignment-operator, when you're comparing the user-input, with the options to choose. You need to use the compare-operator instead. To optimize the code, I would prefer to use a switch-statement, instead of if's (there by the way, should have been if...elseif...else).
Code:
#include <stdio.h>
/* This is just a little thing, to make our application nicer */
#define SEPARATOR "------------------------------------\n"
int main()
{
int i, c, type;
type = 0; /* We need to initialize the type-variable */
/* There isn't a big difference on int's and char's, so we don't */
/* need to use the ASCII-code, we can just you the real character */
while(type != 'q')
{
printf("ASCII character program\n\n");
printf(" Input 1, 2, 3, or q\n");
printf(" 1: ASCII code -> CHAR\n");
printf(" 2: CHAR -> ASCII code\n");
printf(" 3: DISPLAY ASCII TABLE\n");
printf(" q: End of this Program\n");
printf(" >> ");
/* I see in your if-statements, you're using the ASCII-codes, */
/* that means, we've to scan the _character_ using %c */
scanf("%c", &type);
/* Separator */
printf("%s", SEPARATOR);
/* Flush everything in STDIN, so it don't keep it, */
/* until the switch */
fflush(stdin);
/* This is our switch-statement */
switch(type)
{
/* If the user choose '1' */
case '1':
printf("ASCII code -> CHAR\n");
printf(" Input ASCII code: ");
scanf("%d", &c);
printf(" Character for ASCII code %d is -> '%c'\n\n", c, c);
break;
/* If the user choose '2' */
case '2':
printf("CHAR -> ASCII code\n");
printf(" Input CHAR: ");
scanf("%c", &c);
printf(" ASCII code for character '%c' is -> '%d'\n\n", c, c);
break;
/* If the user choose '3' */
case '3':
printf("ASCII code table for 1-127\n");
for(i = 1; i <= 127; i++)
printf("Character for ASCII code %d is -> '%c'\n", i, i);
break;
/* If the user choose non of above */
default:
printf("Invalid option, try again...\n");
}
/* We need to flush again, before next round */
fflush(stdin);
printf("%s", SEPARATOR);
}
}
That's how I would do it. As you can see it's using a switch-statement instead of the if-statements. It's usually a good idea to use a switch-statement, if there's many options. But there isn't so many in this one, so we could had used if...elseif...else-statement.
By the way, which compiler are you using? I've never seen comments like this;
Code:
int var = 10; * This is a comment *
Like you're using in your code. It isn't standard C, so stop using it.
Code:
C:
/* COMMENT */
C++:
// COMMENT
/* COMMENT */
Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum