Leaving switch in while(1)

break loop from switch java
switch case
switch case in while loop java
c# exit while loop from switch
exit while loop java
switch in c
break out of loop in switch statement
exit in switch case in java

I need switch case in while. Every case in the switch is part of the menu which does something. Also I need to handle all the inputs from switch, so default isn't good choice for me. I need to leave while completely when user press CTRL + Z in CMD, where program is happening in order to free memory and quit program. This code is only simplified version of mine. Could you please help me? It's the last thing I need to do to have completed task. Thank you.

while (1) {
    scanf("%c", &choose);

    switch (choose) {

    case 1:
        //something
        break;
    case 2:
        // something
        break;

    // no default!

    }
}

If the user presses Ctrl+Z on Windows, your program will see that as an end of input file (stdin). When scanf tries to read a byte from stdin, it will fail and return -1 (EOF), while the usual return value is 1 (i.e. number of items read).

So you can use the following code:

while (scanf("%c", &choose) == 1)
{
    switch (choose) {

    case 1:
        //something
        break;
    case 2:
        // something
        break;

    // no default!

    }
}

I put the return value of scanf into the while's condition. When scanf cannot read a byte from stdin anymore, the loop will terminate.

How to break out of a loop from inside a switch?, The while loop declaration should explicitly state the only exit condition. Option #1. Readily insert the pause: while( isValidState() ) { execute(); sleep(); } for (;;) { switch(msg->state) { case MSGTYPE // code continue; // continue with loop� Should I leave the switch on sleep while docked overnight or completely turn off the switch before i go bed to sleep? also Is it safe to leave it on sleep overnight? I am leaving it undocked and powered off for now to make sure not to cause any damage to the battery. I don't really know whats normal for the switch. Anything helps thanks!

Your problem in handling control-Z is not leaving the switch statement, it is leaving the while statement.

On a Windows system, when the user presses control-Z at the start of an input line, the software will act similarly to an end-of-file. Notably, when scanf("%c", &choose); executes, there will be no input for it to read, so nothing will be stored in choose. Instead, scanf will return EOF to indicate no match to "%c"could be made (because no input was available). However, your code does not test the return value of scanf, so it will not see this. One way to fix this is:

while (1)
{
    int n = scanf("%c", choose);
    if (n != 1) // Did scanf match %c and store something in choose?
        break; // No, so break out of the while loop.
    switch (choose)
    …
}

Then there is the matter of what should be in the switch statement. You say you "need to handle all the inputs from switch." A char typically has 256 possible values. So, unless you have 256 case labels in the switch, you are not handling all the inputs in the switch statement. You should have a default label.

If any of the cases inside the switch needs to cause execution to leave the while statement, you can arrange this in various ways. One way is to use a variable to indicate that:

while (1)
{
    int n = scanf("%c", choose);
    if (n != 1) // Did scanf match %c and store something in choose?
        break; // No, so break out of the while loop.

    int LeaveWhile = 0;
    switch (choose)
    {
        case 'A':
            // Code to handle A input.
            break;
        case 'B':
            …
        case something:  // Some case where we want to end the loop.
            LeaveWhile = 1; // Indicate end of loop.
            break;
        …
        default:
            // Code to handle remaining values.
            break;
    }

    // If it is time to leave the while loop, break out of it.
    if (LeaveWhile)
        break;
}

How do you exit from a while loop from a switch case? [ANSWERED , Suppose I have a program in a while loop. Inside this loop, there exists some switch cases, like this: while(true) { cin>> n; switch(n) { case 1:� The Nintendo Switch console can be left in the dock while not in use to ensure that it is fully charged. If you put the console in the dock or plug in the AC Adapter directly to charge before the

Before describing how I would handle the problem of the "break" keyword being overused in C, there is another issue you may hit that should be mentioned.

The behavior of control-C and control-Z vary with the OS and the TTY (console) settings.

Linux, with default TTY settings, will cause an interrupt with control-C, which if not handled will end the program. control-Z will suspend the program. By default, in neither case is the character delivered to the program, and so it can not be read by scanf, and it will not be dispatched by the switch statement.

Windows will also interrupt with control-C by default.

I mention this because you depend on reading control characters in your input parsing. If you aren't having the behavior you want, consider looking at TTY settings.

As for exiting the "while(1)" from inside the switch, the standard way is to change the loop from "while(1){}" to "int looping =1; while (looping){}", and set looping to 0 inside the body of the while loop.

In some cases, I will do this with (cover the eyes of the children watching) a goto to a label after the while body. I prominently display goto label, and reverse indent it to outside the level of the while loop body.

Sometimes the break condition is more natural, and sometimes the goto is clearer. If you don't have an aesthetic preference for one over the other, you might default to the break condition rather than the goto.

switch() inside while(), #include<stdio.h> int main() { int ch; printf("Enter 4 to exit\n"); while((ch=getchar()) !=4) { switch(ch) { case 1: printf("Inside the case 1\n"); break;� while(1) { delay(10000); //To delay for 10 seconds. break; } If you can't use delay() then probably use some loop to get significant amount of time delay and thereafter break the loop.

Add a flag at the top of the loop that gets set when you want to break out, then do so after the switch:

while (1) {
    int breakout = 0;

    scanf("%c", &choose);
    switch (choose) {
    case 1:
        //something
        break;
    case 2:
        // something else
        // exit the loop in this case
        breakout = 1;
        break;
    }
    if (breakout) break;
}

How to use C# while loop - CSharp, When count greater than 2 the program will exit from while loop and goto next statement. int count = 1; while (count <= 4) { Console.WriteLine("The value of i is : " +� @kyleforrester87 Technically they could. But the system is under-clocked in handheld mode for obvious reasons. But I don't think there's a point to it when the screen can't even display 1080p, or

you have also *do - while* loop.

bool continueLoop = true;

do
{
    switch(something)
    {
        case smth1:
            /* ... */
            break
        case smth2:
            /* ... */
            continueLoop = false;   //whis will exit the loop
            break;
        default
            /* ... */
             break;
    }
}while(continueLoop)

5.8 — Break and continue, The break statement causes a do, for, switch, or while statement to terminate. std::cout << "Enter 0 to exit or anything else to continue: "; return 1; // return will cause the function to immediately return to the caller (in this case, main()). }. The switch can handle it, but it's draining energy. If you don't plan on playing for a while, save the game and turn your switch off.

Control statements, This keyword is used in, for loops, do loops, while loops and Switch statements. switch ( expression ) { case 1 : Statements1; break; default : DefaultStatements; break; } When a return statement is encountered, control leaves the function� But practically, it is not advisable to use while (1) in real-world because it increases the CPU usage and also blocks the code i.e one cannot come out from the while (1) until the program is closed manually. while (1) can be used at a place where condition needs to be true always.

C# while Loop, C# provides the while loop to repeatedly execute a block of code as long as the specified C# - Switch � C# - For Loop � C# - While Loop � C# - Do-while Loop � C# - Inside a while loop, the value of i increased to 1 using i++ . Use the break or return keyword to exit from a while loop on some condition, as shown below. The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return.

BREAK, way to immediately exit from a loop (FOR, FOREACH, WHILE, REPEAT), CASE , or SWITCH statement This example exits the enclosing WHILE loop when the value of i hits 5. PRO count. I = 0. PRINT, 'Initial value: ', i. WHILE (1) DO BEGIN Use only one battery at a time. On odd days, use Battery #1, then use Battery #2 on even days. Assuming we’ve spent the same day on the water using Battery #1, at the end of the day we can use fully charged Battery #2 to start the engine. Over the course of the season, you’ll use both batteries equally.

Comments
  • Are you actually going to have 256 case labels? If not, you are not handling all possible inputs in the switch statement, and you should have a default case.
  • Is this switch refactorable into function? This will always be a cleanest approach.
  • scanf here will read useless newline bytes, so it's important to do nothing in this case. I guess the program will also ignore all the other unrecognized characters too, so no default needed.
  • Put a break after the switch and continue inside the cases in the switch is an option? Or, sometimes using a goto makes the code cleaner than a more structured option.
  • wouldn't it be scanf(" %c", &choose); ? and choices cannot be 1 or 2 because a char is scanned, not an integer.
  • @Jean-FrançoisFabre: If we believe OP’s claim they have to handle all values, then they will handle space, tab, newline, and all other characters.
  • It might be possible to press Ctrl+A for case 1 :)
  • The fact that the user interface does something when the user presses control-C other than sending a control-C character to the program does not mean the program cannot receive a control-C character. Commonly, pressing control-V control-C will send a control-C character.
  • @EricPostpischil, I agree that one can receive a <cntl>-C. Doing so is not just like receiving most other characters -- either the TTY setting or some other special action is required. I judged the OP to be relatively new to programming, and may not have been familiar with special character processing in the OS. If I am wrong I apologize to the OP. I meant no offense. I was trying to anticipate a next likely problem.
  • They should also test the return value from scanf. If the user presses control-Z (at the start of a line), scanf will return EOF, and it will not store a value in choose.
  • The problem is that none of cases is there to close program. Its only for functions of list structure.
  • wouldn't it be scanf(" %c", &choose); ? and choices cannot be 1 or 2 because a char is scanned, not an integer.