I'm learning C and I created a small program which outputs the ASCII code of the entered character or outputs the character from ASCII Code entered. It first asks the user whether they want to convert Character to ASCII Code or ASCII Code to Character.
I don't know what the problem is in my code. When I run it as a separate file, it works fine.
# include <stdio.h>
int main(void) {
char character;
printf("Enter a character: \n");
scanf("%c", &character);
printf("The character you entered: %c\n", character);
printf("ASCII code of %c is %d\n", character, character);
}
The above code works fine. This is the code which converts character to ASCII Code.
Here's the code which has the option to choose which one to run :
#include <stdio.h>
int main(void) {
char option;
printf("-------- MENU --------\n");
printf("1. Get ASCII code of a character.\n");
printf("2. Get character from ASCII code.\n");
printf(": ");
scanf("%s", &option);
if (option == '1') {
char character;
printf("Enter a character: \n");
scanf("%c", &character);
printf("The character you entered: %c\n", character);
printf("ASCII code of %c is %d\n", character, character);
}
else {
if (option == '2') {
int number;
printf("Enter a Number: \n");
scanf("%d", &number);
printf("The number you entered: %d\n\n", number);
printf("The ASCII character with code %d is %c\n", number, number);
}
else {
printf("Invalid Input !\n");
}
}
}
The above code asks the user to type in 1 or 2 to decide to run Convert Character to ASCII Code or Convert ASCII Code to Character. When I run this code, If I choose option 2, it works just fine and gives me a proper result and if I give 3 or any other invalid option, it gives me "Invalid Input !" printed on the screen. But, when I choose option 1, It just prints out this
-------- MENU --------
1. Get ASCII code of a character.
2. Get character from ASCII code.
: 1
Enter a character:
The character you entered:
ASCII code of
is 10
I don't know what the problem is. Please help me figure it out.
Aucun commentaire:
Enregistrer un commentaire