Problem when going back to main menu - C programming - c

When this program is executed and case 1 is chosen, a submenu will be displayed. In this submenu there is an option to go back to the main menu, now this isn't displaying properly when chosen as it seems to be displaying the main menu twice as well as the default. This is the code:
#include <stdio.h>
#include "functions.h" //calls the functions.h file
int switch1();
int switch2();
int main() {
//Declaring variable
char command;
do {
do {
printf(SPLIT);
printf("\nEnter choice to operate one of the following functions.\n");
printf("1 - Operate using integer representation\n");
printf("2 - Operate using textual representation\n");
printf("0 - Quit\n");
printf("Choice:");
scanf("%c", &command);
switch (command) {
case '1':
switch1(); //Executes function switch1
break;
case '2':
switch2(); //Executes function switch2
break;
case '0':
printf(SPLIT);
printf("\nQuitting.");
printf(SPLIT);
return 0; //Program stops
default: //Switch statement reaches default if no other cases are reached
printf("\nIncorrect input, please re-try.\nEnter choice\n");
break;
}
} while(command != '0');
} while (command < '0' || command > '2');
return 0;
}
int switch1() {
//Declaring variables
char command;
int *array, *iZeroed = NULL;
printf(SPLIT);
printf("\nInteger representation will be used!\n");
array = generate(); //Executes function generate and sets the return to be array
do {
do {
printf("\nChoose an option:\n");
printf("1) Shuffle the array\n");
printf("2) Sort the array\n");
printf("3) Zero an element from the array\n");
printf("4) Display previous zeroed out element\n");
printf("0) Go back to main menu\n");
printf("Choice:");
scanf(" %c", &command);
switch (command) {
case '1':
array = shuffle(array); //Executes function shuffle and sets the return to be the new array
break;
case '2':
array = sort(array); //Executes function shuffle and sets the return to be the new array
break;
case '3':
iZeroed = shoot(array); //Executes function shoot and sets the return to be the element changed to 0
break;
case '4':
target(iZeroed); //Executes function target
break;
case '0':
return 0;
default: //Switch statement reaches default if no other cases are reached
printf(SPLIT);
printf("\nIncorrect input. Please re-enter an option\n");
break;
}
} while (command != '0');
} while (command < '0' || command > '1');
return 0;
}
This is the output I am getting when I choose to go back to main menu:
====================================================================
Choose an option:
1) Shuffle the array
2) Sort the array
3) Zero an element from the array
4) Display previous zeroed out element
0) Go back to main menu
Choice:0
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:
Incorrect input, please re-try.
Enter choice
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:

Place a space character int the format string for scanf() before the input specifier %c, and it means scanf() should drop whitespace characters there.
You are already doing so in your switch1() function, so you should also do so in your main() function.

printf("Choice:");
scanf("%c", &command);
Make it " %c"

Related

Need to loop switch statement until 1 or 2 is entered

I need to loop the switch statement until 1 or 2 is entered as an input. Any help would be nice or sample code. I tried to use a while loop and it kept crashing. I tried a do while as well and it turned into an infinite loop so I must be doing something wrong.
int main (void)
{
int choice; // choice to run program from start menu or quit
while (1)
{
// Menu for entering resistor and capacitor values
printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
printf("Please enter two resistor values in between ");
printf("1 kOhms and 100 kOhms and a capacitor value\n\n");
//Start of menu
printf("Menu\n\n");
printf("1. Continue\n");
printf("2. Exit\n");
scanf("%d", &choice); // User inputs value
switch (choice)
{
case 1:
resistor(); // Program resistor is run if 1 is input
break;
case 2:
printf("Goodbye."); // Program ends if 2 is input
break; // break is used to exit while loop
default:
printf("Sorry I do not understand\n\n");
fflush(stdin); /* clears input buffer to allow user to input a new value if anything other
than 1 or 2 is input into scanf */
}
break;
}
return 0;
}
The problem is that you have a "break" right at the end of your "while", so it's only executed once.
It has been a long time since I did program in C, but if I remember correctly you should avoid using "fflush()" since it has an undefined behavior. Instead, you can change your "scanf()" to be something like:
scanf(" %d", &choice); // User inputs value
That way, you have the same supposed effect of the "fflush()" at the same time of having a cleaner code.
You can use this code
for(;;) {
// Menu for entering resistor and capacitor values
// Start of menu
// User inputs value
if(choice == 1) { ... break; }
else if(choice == 2) { ... return 0; } // If you use the break,the for loop will be stopped or You can use return 0; to return the whole function
else { ... break; }
}
or, also you can use this code
for(;;) {
switch(choice ) {
case 1: ... break;
case 2: ... return 0; // If you use the break, only switch statement is stopped. You can use return 0; to return the whole function
default: ... break;
}
}
Edit :
#include <stdio.h>
int main (void)
{
int choice; // choice to run program from start menu or quit
// Menu for entering resistor and capacitor values
printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
printf("Please enter two resistor values in between ");
printf("1 kOhms and 100 kOhms and a capacitor value\n\n");
while (1)
{
//Start of menu
printf("Menu\n");
printf("1. Continue\n");
printf("2. Exit\n");
scanf("%d", &choice); // User inputs value
switch (choice)
{
case 1: // Program resistor is run if 1 is input
break;
case 2: printf("Goodbye."); // Program ends if 2 is input
return 0; // return 0; is used to exit while loop
default: printf("Sorry I do not understand\nStart Again !\n");
// fflush(stdin); /* clears input buffer to allow user to input a new value if anything other than 1 or 2 is input into scanf */
break;
}
printf("\n");
}
return 0;
}

How Terminate the Program on Pressing Enter key in C?

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');

Little bit confused with the Switch Statements

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;

Terminate program in C

Could someone help me with my code?
My program isn't terminating. After choosing a brand, it should terminate but it loops forever.
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
exit(0);
}
}
return 0;
}
I guess you are misunderstanding the default case of switch: it is executed only if number is not 0,1,2,3.
If you want to exit each time a exit(0) for each case 0 1 2 3
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
exit(0);
break;
case 1:
printf("You have selected proace.\n");
exit(0);
break;
case 2:
printf("You have selected yonex.\n");
exit(0);
break;
case 3:
printf("You have selected reebook.\n");
exit(0);
break;
default:
printf("Please try again.\n");
}
}
return 0;
}
BTW a better code should be
#include<stdio.h>
int main (void)
{
int number;
bool canExit = false;
while (canExit == false)
{
canExit = true;
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
canExit = false;
}
}
return 0;
}
Replace while (count<3) with a boolean, bool loop=true; followed by while (loop). And then inside the switch when you wish to exit, don't call the exit function but simply set loop=false;.
Your break in the switch() exits the switch() but does not exit the while().
If you enter 0, default: case won't be executed.
Is it really what you wanted ?
int number=4 ;
while (number > 3)
and you can delete count, which I can't see is being used anywhere
Actually, the following structure might be better, since you won't have to put an arbitrary number in the comparison:
int number;
do {
// the thing
} while(number > 3);
In this case, it determines whether to continue the loop AFTER the first execution rather than before it. So in a do-while it will ALWAYS execute the do ONCE before the condition can break it, even if the condition is false to begin with!
I would replace your switch with:
char* brand[] = { "proace", "yonex", "reebook" };
do{
if(number == 0)
printf("exit.\n");
else if(number <= 3)
printf("You have selected %s.\n", brand[number]);
else
printf("Please try again");
}while(number > 3);
Encapsulate it in do-while loop with condition number > 3 and it will loop until user select 0-3. In this case, exit(0) is unnecessary.
You are not updating the count variable that is why it is not exiting. For exiting the while loop the count should be greater than or equal to 3.
As long as you will be giving the input 0, 1, 2 or 3 you will never reach default which has exit() and thus the program will continue to run as we have set while conditional as (count < 3) i.e. 0 < 3 which is always true. So no chance of exiting the program by while conditional. The only chance to terminate the program is from default.
So if you give input anything other than 0, 1, 2 or 3, you will reach default which will call exit() and thus will cause the program to terminate.
Hello you can exit your program by including the header file #include in your header file section.
Then you can use the exit() command
Eg :-
#inlcude<process.h>
#include<studio.h>
into opt;
printf(" enter o ");
scant(" %d",&opt);
switch(opt)
case 0: printf(" exiting the program");
getch();
exit();

do while loop in C

I am implementing a polynomial using array. This is the Problem Statement:
Write a menu-driven program to represent Polynomials as a data structure using arrays. and write functions to add, subtract and multiply two polynomials; multiply a polynomial with a constant, find whether a polynomial is a "zero- polynomial, return the degree of the polynomial. Assume that a new polynomial is created after each operation. How would you input and output polynomials?
I have created the input and output functions. But my do while loop is running twice.. Help me finding out why.
The do-while loop
do{
print_menu();
scanf("%c",&ch);
printf("\nch = %c\n",ch);
switch(ch){
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
}while(ch != 'q');
return 0;
}
The print_menu() function
void print_menu()
{
printf("\n1. Create a new polynomial.");
printf("\n2. Print polynomial.");
printf("\nq. Exit");
printf("\nEnter Choice:");
}
The create_poly() function
void create_poly(int poly[][2], int termpool[][2], int *next_poly)
{
int beg = poly[*next_poly][0];
int end, size, i, j;
printf("Enter size of the polynomial:");
scanf("%d",&size);
poly[*next_poly][1] = beg + size - 1;
end = poly[*next_poly][1];
printf("Enter terms of the polynomial(coeff then exponent):\n");
for(i=beg; i<=end; i++){
for(j=0; j<2; j++){
scanf("%d ",&termpool[i][j]);
}
}
poly[++(*next_poly)][0] = end + 1;
}
The print_poly() function
void print_poly(int poly[][2],int termpool[][2],int *next_poly)
{
int pos,beg,end;
int i;
printf("Enter position of the polynomial:");
scanf("%d",&pos);
if(pos-1 > *next_poly){
printf("Invalid position.");
return;
}
beg = poly[pos-1][0];
end = poly[pos-1][1];
for(i=beg; i<=end; i++){
printf(" %dx^%d +",termpool[i][0],termpool[i][1]);
}
printf("\b = 0");
}
Here is a sample output:
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:1
ch = 1
Enter size of the polynomial:2
Enter terms of the polynomial(coeff then exponent):
2 4
6 7
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:
ch =
Invalid choice.
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:q
ch = q
Tried flushing the stdinā€¦ The problem stays. Printing the value of ch in each step, I think it is a whitespace. Where does the white space comes?
The answer to abnormal behavior of scanf answers this question also.
If you test the next code you will note the same problem
int main() {
char c;
do {
scanf_s("%c", &c);
if (c != 'q')
printf("test scanf() function\n");
} while (c);
}
the scanf() function works when the enter key is pressed, but this insert another char in the buffer input, the char of new line '\n', it is taken again by scanf() because the loop block. Try to change the previous code by this code:`
do {
scanf_s("%c", &c); // or c = getchar();
switch (c){
case '\n':
break;
default:
printf("test scanf() function\n");
}
} while (c);`
and will work fine. In your code only add a new case in the switch block:
switch(ch) {
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case '\n':
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
sorry, English is not my native language
There's an extra character waiting to be consumed after you make your initial choice, that's why the loop is executing twice.
See this question on the comp.lang.c FAQ

Resources