I'm writing a program which allows user to enter alphanumeric strings and validate their input based on the options available.when I run my code below, it always print option is invalid even though I have entered an option within the range.Can anyone help me with this?Any help will be aprreciated.
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main (void){
char option;
do{
printf("\n\n----------------------------------------------------\n");
printf("Main Menu\n");
printf("----------------------------------------------------\n");
printf("1. Add Record\n");
printf("2. Delete record\n");
printf("3. List Record\n");
printf("4. Exit\n");
printf("----------------------------------------------------\n");
printf("Enter your option:");
scanf("%c",&option);
if(isdigit(option)){
switch(option){
case 1:
add();
break;
case 2:
del();
break;
case 3:
listrec();
break;
case 4:
return 0;
default:
printf("The number that you have entered is invalid.Please enter a new option\n");
break;
}
else{
printf("The option that you have entered is invalid.Please enter a new option\n");
}
}while(option!=4);
return 0;
}
Besides using 1 instead of '1' (you need to compare the character with the character, not with a number), there is another problem - you don't get the carriage return from the input, and this makes the input fail on the second pass. See below for a possible solution:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main (void){
char option;
do {
printf("\n\n----------------------------------------------------\n");
printf("Main Menu\n");
printf("----------------------------------------------------\n");
printf("1. Add Record\n");
printf("2. Delete record\n");
printf("3. List Record\n");
printf("4. Exit\n");
printf("----------------------------------------------------\n");
printf("Enter your option:");
if(scanf("%c",&option)==1) {
if(isdigit(option)){
printf("you entered %c\n", option);
switch(option){
case '1':
printf("adding\n");
break;
case '2':
printf("deleting\n");
break;
case '3':
printf("listing\n");
break;
case '4':
return 0;
default:
printf("The number that you have entered is invalid.\nPlease enter a new option:\n");
break;
}
}
else {
printf("you entered not a digit: %c\n", option);
printf("The number that you have entered is invalid.\nPlease enter a new option:\n");
}
// empty the input buffer:
while(getchar()!='\n');
}
}
} while(option!=4);
return 0;
}
A few things to note:
There was a } missing in your code sample given - between the end of the switch and the else
I check that scanf returns a value of 1 (valid conversion) - per Nisse's comment
I empty the input buffer after the if by reading until I get an EOL (which stays in the buffer after the scanf). This ensures that the next character read is the next character after the carriage return, and not the carriage return itself.
Miscellaneous clean-up...
The integer value of a character object that contains a digit is equal to the internal representation of the corresponding character that denotes the digit. For example if the ASCII coding is used then for example '1' has internal representation equal to 49. So you had to write
case 49:
instead of
case 1:
Change case labels the following way that they would not depend on the internal representation of character digits.
case '1':
add();
break;
case '2':
del();
break;
case '3':
listrec();
break;
case '4':
return 0;
default:
printf("The number that you have entered is invalid.Please enter a new option\n");
break;
}
else{
printf("The option that you have entered is invalid.Please enter a new option\n");
}
}while(option!='4');
Related
I'm trying to make a calculator with 12 operations, the 12th being exit, and I want it to produce an error message if the user tries to input a value other than 1-12.
I got it to work for numbers like 15, 500, etc. that aren't in the range, but if the user inputs the letter 'a' for example, it results in an infinite loop, while if the user enters 500 it does what I want it to, which is print the "try again" message and display the menu again.
So, I know the problem is with the if/else loop directly contained in the while loop, but I'm not sure why it doesn't return to the menu after the break; statement in the else statement containing "red" (I put red and blue so that I could tell which statement is being printed). I tried a do/while loop but had the same issue. I also tried making the default statement in the switch case be the "try again" part, and it works if the user enters a number like 500, but as soon as a letter or character like ? is entered, I get an infinite "try again" loop.
This is the code I'm having trouble with:
#define RESTRICT(option, min, max) (option > min && option < max)
while(!exit) {
printf("Choose an option:");
printf("1. Eliminate.");
printf("2. Show fraction.");
printf("3. Show all fractions.");
printf("4. Show the absolute value.");
printf("5. Simplify.");
printf("6. Add.");
printf("7. Subtract.");
printf("8. Multiply.");
printf("9. Divide.");
printf("10. Save in archive.");
printf("11. Load in archive.");
printf("12. Exit program.");
if(scanf("%i", &option) == 1){
if(RESTRICT(option,0,12)){
switch(option){
case 1:
printf("Example");
break;
case 2:
printf("Example");
break;
case 3:
printf("Example");
break;
case 4:
printf("Example");
break;
case 5:
printf("Example");
break;
case 6:
printf("Example");
break;
case 7:
printf("Example");
break;
case 8:
printf("Example");
break;
case 9:
printf("Example");
break;
case 10:
printf("Example");
break;
case 11:
printf("Example");
break;
}
} else if (option==12){
printf("\nGoodbye!\n");
exit=1;
} else {
printf("\nThat is not an option! Try again\n");
printf("\nBlue\n");
continue;
}
} else {
printf("\nThat is not an option! Try again\n");
printf("\nRed\n");
break;
}
}
'a' for example, it results in an infinite loop"
'a' is never consumed by if(scanf("%i", &option) == 1){. It is not numeric text, so gets put back into stdin for the next input function. Since scanf("%i", &option) if then call again, the results repeat.
Code needs to read and consume the 'a'. Consider fgets().
Best to avoid using scanf() at all until you understand why it it bad.
According to your code, In this code scanf("%i", &option) expects interger value from the use end. when user enter non-integer value, scanf function will not store anything in the option variable. use fgets The fgets function reads a text line or a string from the specified file or console. And then stores it to the respective string variable.
Try to update your code as follows:
char input[10];
while (!exit) {
printf("Choose an option:");
printf("1. Eliminate.");
printf("2. Show fraction.");
.
.
.
fgets(input, sizeof(input), stdin);
if (sscanf(input, "%i", &option) == 1) {
if (RESTRICT(option, 0, 12)) {
switch (option) {
case 1:
printf("Example");
break;
case 2:
printf("Example");
break;
.
.
.
}
} else if (option == 12) {
printf("\nGoodbye!\n");
exit = 1;
} else {
printf("\nThat is not an option! Try again\n");
continue;
}
} else {
printf("\nThat is not an option! Try again\n");
}
}
i am making a small project in which I have to convert different values to different bases like 10,8,16.But the problem is that I want to run the program till the user press 6 but if user hit Enter key then too it is waiting for the input rather than simply terminating. I'm using C11 version of C on online compiler.
and here's my code.
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
I have made a separate file in which I have made functions and I thought it isnot necessary to put that code here too.
Consider using fgets to take input into a character array.
If needed, the input can be parsed with sscanf, strtol or others.
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
To solve the enter problem:
scanf("%d", &choice)
Right now you are taking int value, try with char value and match the enter key with it. Then you'll be able to do what you are trying to do.
Ok, So I wanted to terminate the program if Enter key is pressed. So I was first a newbie then I realized that itsnot a big deal and to do so I just need to take a char as Input and then check that if that char input is enter key or not.
Its a sample code to terminate the program after pressing enter key.
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
But if your program doesnot take input then you should clear the buffer before the above provided code by adding just this single line before the above code.
while(getchar()!='\n');
void menu(){
printf("\n");
printf("1. Convert integers in decimal number system to binary numbers \n");
printf("2. Compute a consecutive square root expression \n");
printf("3. Solve a quadratic equation \n");
printf("4. Print something fun \n");
printf("q. Quit\n \n");
printf(" Enter your choice: ");
}
main () {
char choice;
do {
menu();
scanf("%c", &choice);
switch (choice){
case '1':
...
case '2':
....
case '3':
...
case '4':
....
default:
printf("Wrong choice. Please enter again: ");
break;
}
}
while (choice != 'q');
}
Here is my general idea, but I can't get it to prompt the wrong choice and repeat the menu. When I enter a wrong choice, the output is as follows:
For example, I entered 5:
Enter your choice: 5
Wrong choice, please enter again:
1. Convert integers in decimal number system to binary numbers
2. Compute a consecutive square root expression
3. Solve a quadratic equation
4. Print something fun
q. Quit
Enter your choice: (this is where I get to input)
Take a look at the below changes:
Change your scanf() as
scanf(" %c",&choice);
A space before the %c will make sure all special characters including newline is ignored.Without this everytime there is a newline in the buffer to and scanf reads from it and you will see that your look doesn't work as expected.
After this please make sure once the default case is hit you need to break from the while() loop.
do {
menu();
scanf(" %c", &choice);
switch (choice){
case '1':
break;
case '2':
break;
case '3':
break;
case '4':
break;
default:
{
printf("Wrong choice. Please enter again: ");
break;
}
}
}
while (choice != 'q');
First thing, Put break; in each case so only the case you choose will apply. To solve the printing 2 times issue, just Change the %c in scanf("%c", &choice); to %s >> scanf("%s", &choice);
This is the code:
#include <stdio.h>
void menu(){
printf("\n");
printf("1. Convert integers in decimal number system to binary numbers \n");
printf("2. Compute a consecutive square root expression \n");
printf("3. Solve a quadratic equation \n");
printf("4. Print something fun \n");
printf("q. Quit\n \n");
printf(" Enter your choice: ");
}
main () {
char choice;
do {
menu();
scanf("%s", &choice);
switch (choice){
case '1':
printf("1 \n");
break;
case '2':
printf("2 \n");
break;
case '3':
printf("3 \n");
break;
case '4':
printf("4 \n");
break;
case 'q':
break;
default:
printf("Wrong choice. Please enter again: ");
break;
}
}
while (choice != 'q');
}
For example if i enter: "123456-7". The output at the first print statement would be: "123456-7" and at the 2nd print statement it would be "7". Which is correct.
But at any point after the break if I print the array again the print statement would go wrong in the last digit. It would look like: "123456-1" and the second would look like "1".
#include <stdio.h>
int main()
{
int lotoNumbers[6];
int ticketNumbers[6];
char option;
while(option != 'C')
{
printf("Your option:");
scanf(" %c", &option);
switch(option)
{
case 'W': printf("Please enter todays winning ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &lotoNumbers[0], &lotoNumbers[1], &lotoNumbers[2], &lotoNumbers[3], &lotoNumbers[4], &lotoNumbers[5], &lotoNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("----The following numbers matched! %d\n", lotoNumbers[6]);
break;
case 'T': printf("Please enter your ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &ticketNumbers[0],&ticketNumbers[1],&ticketNumbers[2],&ticketNumbers[3],&ticketNumbers[4],&ticketNumbers[5],&ticketNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", ticketNumbers[0], ticketNumbers[1], ticketNumbers[2], ticketNumbers[3], ticketNumbers[4], ticketNumbers[5], ticketNumbers[6]);
break;
case 'C': printf("Computing....\n");
break;
case 'Q': printf("The program will now quit. Thank you for playing LOTO 649.\n");
return (0);
break;
default: printf("You entered an invalid option. The program will now terminate.\n");
return (0);
}
}
printf("The numbers are:%d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("The number is: %d\n", lotoNumbers[6]);
return 0;
}
You didn't allocate enough space for your arrays. The number used to allocate space for an array is the number of entries in the array, not the last index number. Index 6 is the 7th item and is past the end of the array. The value of lotoNumbers[6] is undefined and can change randomly, because the program is using that memory for something else.
int lotoNumbers[6];
int ticketNumbers[6];
That 6 should be 7.
I am trying to store character as well as integer numbers in the same region through character pointer however, I am not getting the intended result. It is displaying only characters.
Here, I have created a character pointer which should contain atleast both characters and
integers, then should display them properly.
int main()
{
char c,store[30];
char *p=malloc(30);
int choice,i=0,n;
p=store;
while(1)
{
printf("\n********Menu**********");
printf("\n1.Enter a character");
printf("\n2.Enter a Number");
printf("\n3.Enter a double");
printf("\n4.Display the values");
printf("\n0.Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter a character:");
fflush(stdin);
scanf("%c",&c);
*p=c;
p++;
break;
case 2:
printf("\nEnter a Number");
scanf("%d",&n);
*p++=n;
break;
case 4:
*p--='\0';
for(i=0;store[i];i++)
printf("%c",store[i]);
break;
case 0:
exit(0);
break;
}
}
getch();
return 0;
}
You can't simply write doubles and int into a char array.
However with following you could see 0-9 :
case 2:
printf("\nEnter a Number"); //Just for 0-9
scanf("%d",&n);
*p=n+48; //Convert to ascii
p++;
break;