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");
}
}
Related
This is a queue sample.This is working but when I select the choose 1 I can not select choose 2 anymore I know I need a while loop but I could not do that in the correct way.
printf_s("? ");
scanf_s("%d", &choose);
In here I need to add a loop I guess but I could not do that properly.
while (choose != 3) {
switch (choose)
{
case 1:
printf_s("Enter a character:");
scanf_s("\n%c", &chooseNo);
add(&startPtr, chooseNo);
printList(startPtr);
break;
case 2:
if (!Isempty(startPtr)) {
printf_s("Enter a character for deleting ");
scanf_s("\n%c", &chooseNo);
if (delete(&startPtr, chooseNo)) {
printf_s("%c deleted.\n", chooseNo);
printList(startPtr);
}
else
printf_s("%c could not be found.\n\n", chooseNo);
}
else
printf_s("List is empty.\n\n");
break;
default:
printf_s("Invalid choose.\n\n");
menu();
break;
printf_s("?");
scanf_s("%d", &choose);
}
}
return 0;
}
First of all, don't put all your code in. It's like 100~200 lines, from which a half is useless in order to solve your problem.
Your scanf for editing the value of choose in the loop is in the wrong place.
What happens is :
while (choose != 3) {
switch (choose) {
case 1:
//code for case 1
break; // if the user chose 1, the program end the switch statement here
case 2:
//code for case 2
break; // if the user chose 2, the program end the switch statement here
default: // For any choice but 1 or 2, this part is executed
printf_s("Invalid choose.\n\n");
menu();
break; // For the default case, the switch statement ends here
// Any code written after this point will not be reached at all
printf_s("?"); // unreachable code
scanf_s("%d", &choose); // unreachable code
}
}
So, just write :
while (choose != 3) {
switch (choose) {
/* Code of your switch statement */
}
printf_s("?");
scanf_s("%d", &choose);
}```
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');
I'm very new to C programming, and I need a help!
I have made a program of calculator with the help of Switch Statement and I want this program to be in a loop, So that it ask the menu (i.e Enter your Choice: Divide,Multiplication,Addition etc) again and again with the user.
Also I want, an End option with the Cases in Menu, which will close the program. I don't know how to code that End option which will make the Program Close.
Please Help!
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,choice;
float sum,mul,div,sub,quo;
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
printf("Enter the Second Number: ");
scanf("%d",&b);
printf("\n Enter Your Choice");
printf("\n\n1.Sum");
printf("\n2.Multiplication");
printf("\n3.Division");
printf("\n4.Subtraction");
printf("\n5.Quotient");
printf("\nYOUR CHOICE: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
sum=a+b;
printf("Sum= %f\n",sum);
break;
case 2:
mul=a*b;
printf("Multiplication= %f\n",mul);
break;
case 3:
div=a/b;
printf("Division= %lf\n",div);
break;
case 4:
sub=a-b;
printf("Subtraction= %f\n",sub);
break;
case 5:
quo=a%b;
printf("Quotient= %f\n",quo);
break;
default:
printf("\n Unavailable Choice");
}
return 0;
getch();
}
Assuming you add option number 6 to close the calculator, you can add the following case to quit the program -
case 6:
// print bye message or whatever
exit(0);
break;
You can read about the exit function and what the arguments passed to it mean. Usually a 0 indicates successful exit from the program.
You also need to include stdlib.h if you want to use exit.
I would suggest introducing a loop condition variable, eg. CarryOn, initialise it to 1, and use that in a while loop. Let the loop continue as long as the variable is 1. When the user selects "End", set the variable to 0 in the case. That will end the loop.
Let me clarify it with some example code outline:
int CarryOn = 1;
while (CarryOn == 1)
{
// ...your original code
// ...
// add to switch
case 6: // 6 will be the "End" / "Exit" option
CarryOn = 0;
break;
}
You will need to have a while loop.
while(true){
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
....
//return 0; remove the return statement
getch();
}
and also add the menu item 6) Exit to your printf and handle that option as described in the one of the answers above.
case 6:
// print bye message or whatever
exit(0);
break;
This section of code is supposed to display a menu with two options, read the input and go to the corresponding function. If the user enters something other than 1 and 2 the program should warn the user and show the menu to ask user to enter the input again. This process will keep repeating until the user puts the right input.
I'm trying to find a way to repeat the loop only when the user inputs something other than 1 and 2 (so that the user can enter the appropriate response this time).
However, when I use a while loop like this, it loops no matter what the input is.
Any help is much appreciated.
char input;
displayWellDoneMenu();
scanf("%c", &input);
while (input != '1' || input != '2')
{
printf("You must select 1 or 2!\n");
displayWellDoneMenu();
scanf("%c", &input);
rewind(stdin);
system("cls");
}
switch (input)
{
case'1':
additionIntermediate();
break;
case '2':
main();
break;
}
char input;
do
{
displayWellDoneMenu();
scanf("%c", &input);
system("cls");
if (c=='1' || c=='2')
break;
printf("You must select 1 or 2!\n");
}while(1);
switch (input)
{
case'1':
additionIntermediate();
break;
case '2':
main();
break;
}
This could be an idea:
while(1){
scanf("%c", &input);
if(input == '1' || input == '0') break;
// else continue cycle
}
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');