While,switch, case statement - c

I'm using a while, switch, case statement for my menu and when it runs it keeps saying enter choice, I know while(1) creates an infinite loop but is there a way to avoid this?
while(1)
{
printf("\nEnter Choice \n");
scanf("%d",&i);
switch(i)
{
case 1:
{
printf("Enter value to add to beginning: ");
scanf("%c",&value);
begin(value);
display();
break;
}
case 2:
{
printf("Enter value to add last: ");
scanf("%c",&value);
end(value);
display();
break;
}
case 3:
{
printf("Value to enter before\n");
scanf("%c",&loc);
printf("Enter value to add before\n");
scanf("%c",&value);
before(value,loc);
display();
break;
}
case 4 :
{
display();
break;
}
}
}
Any help would be appreciated.

While(1) is ok. But you have to have some conditions to finish the loop. Like :
while(1){
.........
if(i == 0)
break;
............
}
Add a space at the beginning of every "%d" and "%c",because scanf always leaves a newline characters in buffer:
"%d"->" %d"
"%c"->" %c"

Alternative solution,
int i = !SOME_VALUE;
while(i != SOME_VALUE)
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
switch(i)
{
case SOME_VALUE: break;
.
.
.
// the rest of the switch cases
}
}
SOME_VALUE is any integer number notify to stop loop.

Alternatively, you may want to put a condition in the loop that relates to the input, e.g.
do
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
// the rest of the switch is after this
} while (i != SOME_VALUE);
Note the use of the do loop, which tests the condition at the end, after a value has been read into i.

I would probably write a function that can be called in the loop:
while ((i = prompt_for("Enter choice")) != EOF)
{
switch (i)
{
case ...
}
}
And the prompt_for() function might be:
int prompt_for(const char *prompt)
{
int choice;
printf("%s: ", prompt);
if (scanf("%d", &choice) != 1)
return EOF;
// Other validation? Non-negative? Is zero allowed? Retries?
return choice;
}
You can also find relevant discussion at:
scanf() validation.
What is the reason for error while returning a structure in this C program?
Common macro to read input data and check its validity

Related

C Program, Array inside a case in continuous Switch Menu loop

My array inside case 4 in looping Switch Menu doesn't print/display the value of the last array when the user input goes beyond array[4].
I tried to take the case 4 out and make it a single program to check if it doesn't really work on its own but it works fine, but when I put it back into the Switch, same issue again. I thought that maybe the initialization part is the problem. Help
`
#include <stdio.h>
int main ()
{
char first[20],last[20];
float math,eng,sci,avg;
int a,b,c,d,diff,array[diff],e,i,input;
do{
printf("\nMAIN MENU\n");
printf("[1] Basic Input Output\n[2] Conditional Statement\n[3] Looping Construct\n[4] Array\n[5] About\n[6] Exit");
printf("\n\nChoose: ");
scanf("%d",&input);
printf("\n");
switch (input)
{
case 1:
printf("\nEnter your given name:");
scanf("%s",first);
printf("Enter your surname:");
scanf("%s",last);
printf("\nHello %s %s!\n",first,last);
break;
case 2:
printf("\nEnter your grade in Math:");
scanf("%f",&math);
printf("\nEnter your grade in Science:");
scanf("%f",&sci);
printf("\nEnter your grade in English:");
scanf("%f",&eng);
avg=(math+eng+sci)/3;
if(math>eng&&sci)
{
printf("\nHighest grade is in: Math");
}
if(eng>math&&sci)
{
printf("\nHighest grade is in: English");
}
if(sci>eng&&math)
{
printf("\nHighest grade is in: Science");
}
if(math==eng)
{
printf("\n--Math and English tied grades--");
}
if(math==sci)
{
printf("\n--Math and Science tied grades--");
}
if(eng==sci)
{
printf("\n--Science and English tied grades--");
}
printf("\nYour average in 3 subjects:%f\n",avg);
break;
case 3:
printf("Enter beginning number: ");
scanf("%d",&b);
printf("Enter ending number: ");
scanf("%d",&c);
printf("\nCounting from %d to %d\n",b,c);
while(b<=c)
{
printf("%d ",b);
b++;
}
printf("\n");
break;
case 4:
printf("Enter Starting Series of Numbers: ");
scanf("%d",&a);
printf("Enter Ending Series of Numbers: ");
scanf("%d",&d);
diff=(d-a);
array[diff]=d;
printf("Select Array Value to Display: 0 to %d: ",diff);
scanf("%d",&e);
for(i=0;i<=diff;i++)
{
array[i]=a;
if(i==e)
{
printf("%d\n",array[i]);
}
a++;
}
break;
case 5:
printf("Abouts\n");
break;
case 6:
printf("Thank you!");
break;
}
}while(input != 6);
return 0;
}
`
This should be a comment, but I don´t have enough reputation yet.
As Gerhardh said, the problem is that you use diff before being initialized (which causes undefined behaviour)
As you said, if you move the initialization of array inside the case 4: after diff being set the program should work as intended. If you want to keep it before the switch, try using int* and malloc/free inside the case 4: (and add #include <stdlib.h>) Anyway, you should check diff as positive value before using it to set the size of array
About optimizing the code, you can skip the line array[diff]=d; because you are setting the same value inside the for loop. And you can remove the line a++; if you changes array[i]=a; -> array[i]=a+i;

How can I create loop for queue?

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);
}```

scanf and switch statement debug

All the cases work except the switch 'a' case. The a case runs the insert method below. Any help would be appreciated, thanks. printf statements inside the switch statement don't work.
void insert() {
char name;
printf("enter your name");
scanf("%c", &name);
for(int i = 0; i < LENGTH; i++){
if (!Thesame(names[1], name) == 0 && counter != LENGTH && strlen(name) <= MAX){
for(int j = 0; j < LENGTH; j++){
strcpy(names[counter],name);
}
}
else{
printf("error");
}
}
```
int main() {
while (1) {
char input;
printf("Type in 'a' be added to the system \n");
printf("Type in 'n' to print next patient and remove from
waitlist \n");
printf("Type in 'l' to list the patients on the waitlist \n");
printf("Type in 'q' to quit the program \n");
scanf("%c", &input);
switch (input) {
case 'a':
insert();
break;
case 'n':
next();
break;
case 'l':
print();
break;
case 'q':
return 0;
}
}
}
char name;: name can contain only a single character. So when you type for example: cuq, name will contain c, then insert does whatever with name and then returns to main. Then in main scanf("%c", &input) will read the remaining characters from the input buffer ('u' and 'q') and because of case 'q': the programs stops. Use a debugger or put some printfs at strategic places in your code to see what happens.
You want a string here and you probably want something like this in insert:
char name[100];
printf("enter your name: ");
scanf("%s", name);
...
You also probably need to change the Thesame function.

Double while loop for flushing data before a switch statement

I need to write a script for the user to enter a score between 0 and 10, flush the bad input out, if user inputs it and then using a switch statement, tell a user what grade did he/she got.
Here is my script:
...
int main()
{
int input; // input from user
printf("Enter the number between 0 and 10 and I will tell you your grade!");
while ((input=scanf("Your input:", &input) != EOF))
{
if (input < 0 || input > 10) //input is invalid
{
printf("Sorry, invalid character data.");
while (getchar() !='\n')
{
printf("Your input must be from 0 to 10.", input);
scanf("%d", &input); //This part looks very bad for me
}
}
else
switch (input)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Your grade is F. \n");
break;
case 6:
printf("Your grade is D. \n");
break;
...
I got this far with my homework, and here are some "leftover" problems I can't fight with.
1) Whenever user submits anything after enter, it goes into infinite loop and prints Your grade is F., even when case = 6 for example.
2) I used break; at the end of each case. It looks like they don't work(?)
3) It looks like the problem in the second line in the second loop
scanf("%d", &input); //This part looks very bad for me
but then I guess the scripts accepts it as true since the else statements that includes switch begins to work, because otherwise it wouldn't print Your grade is F.
Try the following code. Have a look at what flush_stream is doing when we have invalid data...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void flush_stream();
void flush_stream() {
char c;
do {
c = getchar();
}
while (!isdigit(c) && c != '\n');
ungetc(c, stdin);
}
int main(void) {
const char *prompt = "Input please: ";
int input; // input from user
printf("Enter the number between 0 and 10 and I will tell you your grade!\n");
while(1) {
printf("%s", prompt);
int ret = scanf("%d", &input);
if(ret == 0) {
printf("Sorry, invalid character data, your input must be from 0 to 10.\n");
flush_stream();
continue;
}
if(ret > 0) {
if (input < 0 || input > 10) {
printf("Sorry, invalid character data, your input must be from 0 to 10.\n");
flush_stream();
continue;
}
switch (input) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Your grade is F. \n");
break;
case 6:
printf("Your grade is D. \n");
break;
}
}
}
}
It seems you are using scanf and printf wrong.
To input a number:
scanf("%d", &input);
To output a number:
printf("%d\n", input);
And in you while loop, when the input is illegal, why not just continue to the next loop?
while (true) {
printf("input your grade here: ");
if (scanf("%d", &input) == EOF) {
break;
}
if (input < 0 || input > 10) {
printf("your input is illegal.\n");
continue;
}
switch (input) {
...
}
}

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