Q&A: How do you exit a loop by using the “enter” key in C?
Question by michaelR: How do you exit a loop by using the “enter” key in C?
I’ve noticed that “enter” key is ’13′ on the ASCII chart, however when i incorporate it into my code it does not work.
For example:
char = op;
scanf(“%s”, &op);
switch (op)
{
case 43:
printf(“It is a plus!\n”);
break;
case 45:
printf(“It is a subtraction!\n”);
break;
case :13
printf(“It is enter!\n”);
break;
43 and 45 work, but for 13 (the enter key) it doesn’t, how can I make it work by pressing the “enter” key?
Best answer:
Answer by BigRez
Try using 10 rather than 13.
Also use %c with the scanf rather than %s
You also have a few syntax errors in the code above.
What do you think? Answer below!
Usually you use ‘break’ statement to exit a loop. In this situation, break statement exits the switch statement. you have to use a variable like this:
char op;
int i;
for ( i = 0; i < 10; i++ )
{
bool shouldExitLoop = false;
char op;
scanf ( “%c”, &op );
switch ( op )
{
case 45:
…
break;
case 43:
….
break;
case 13:
…..
shouldExitLoop = true;
break;
}
if ( sholdExitLoop )
break;
}
Was this answer helpful?
LikeDislikeVery well written post. It will be helpful to everyone who usess it, as well as myself. Keep doing what you are doing – looking forward to more posts.
Was this answer helpful?
LikeDislikeHeya i am for the first time here. I came across this board and I find It truly useful & it helped me out a lot. I hope to give something back and help others like you helped me.
Was this answer helpful?
LikeDislikeI really like it when folks arrive with each other and share opinions, excellent weblog, preserve it up.
Was this answer helpful?
LikeDislikeYou got a very good website, Glad I noticed it through yahoo.
Was this answer helpful?
LikeDislike