switch statement creating infinite loop - c

I am writing a piece of code and in one part of my code I am using a switch statement in C language. if I press n it exits correctly if I press y it will infinite loop the default statement until I press control c. what am I doing wrong here. been changing the while statement but can't find the right one.
int main()
{
char ans;
printf("DO you want to continue?");
scanf("%c", &ans);
do
{
switch(ans)
{
case 'y':
some stuff...
printf("DO you want to continue?");
scanf("%c", &ans);
break;
case'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
return 0;
}

When you press enter, the linefeed character \n is added to the input stream. Your code does not anticipate this, because switch(ans) only handles y, n or “everything else” (which includes the linefeed character).
To fix this, allow scanf to ignore any preceding whitespace by changing your format string to " %c" instead, e.g.
scanf(" %c", &ans);
// ^ space character inserted here
I think it would make more sense to move the scanf call to inside the loop, like this:
int main()
{
char ans;
do
{
printf("DO you want to continue?");
if (scanf(" %c", &ans) != 1)
break;
switch(ans)
{
case 'y':
// some stuff...
break;
case 'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
}
Don't forget to always check the result of scanf(). It will return the number of items successfully scanned (in your case, you want it to return 1). If it returns 0 or a negative number, then another problem has occurred.

Related

Basic C - Switch cases duplication

I am working on a project, where you answer a char, and if it is not one of the 4 answers, it tells you to try again. If it is not the correct one of the 4, it stops running. Here is a snippit.
#include <stdio.h>
#include <stdbool.h>
bool switchCheck = true;
char answer;
printf("A. English\nB. French\nC. Spanish\nD. German\n");
do{
scanf("%c\n", &answer);
switch (answer){
case 'C':
printf("Very nice ");
break;
case 'B':
case 'A':
case 'D':
printf("Sorry! Incorrect. Code Ends\n");
switchCheck =false;
break;
default:
printf("Try Again\n");
}
}while(switchCheck==true);
For some reason, when I input A, B, or D, it first prints the result for default, and if I do it again immediately afterward, it gives me the right input. Any help?
Thanks!
You are using scanf like
scanf("%c\n", &answer);
Instead use
scanf( " %c", &answer );
See the blank before the conversion specifier %c. It allows to skip white spaces.

scanf asking for two values instead of one [duplicate]

This question already has answers here:
scanf() curious behaviour!
(3 answers)
Closed 8 years ago.
When I compile this code, it leads to scanf asking for a value twice when I pick choice A. What am I missing here?
This isn't the first time this is encountered, so I'm suspecting I'm failing to grasp something rather fundamental with scanf.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");
scanf("%c", &choice);
switch (choice)
{
case 'A':
{
int a =0;
printf("you've chosen menu A\n");
printf("enter a number\n");
scanf("%d\n", &a);
printf("%d\n", a);
}
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
}
return 0;
}
scanf("%d\n", &a); should be scanf("%d", &a);
Also read Related question.
In former case after reading an integer and storing into a, scanf's argument string is not exhausted. Looking at \n, scanf would consume all the whitespaces (newline, tab, spaced etc) it sees (And will remain blocked) until it encounters a non-whitespace character. On encountering a non-whitespace character scanf would return.
Learning: Don't use space, newline etc as trailing character in scanf. If the space character is in the beginning of argument string, scanf may still skip any number of white space characters including zero characters. But when whitespace is a trailing characters, it would eat your new line character also unless you type a non-whitespace character and hit return key.
Simply remove the newline character from scanf("%d\n", &a); and it will not ask to enter a value twice
scanf("%d", &a);
Remove a newline character while scanning
// the trailing '\n' in the scanf format string
// is what is causing the dual inputs
// the returned value from I/O statements (I.E. scanf)
// needs to be checked to assure operation was successful
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");
// note
// leading ' ' in format string to consume leading white space
// and no trailing '\n'
if( 1 != scanf(" %c", &choice) )
{ // then, scanf failed
// handle error condition
perror("scanf failed for choice");
exit(EXIT_FAILURE);
}
// implied else, scanf successful
switch (choice)
{
case 'A':
{ // braces needed due to variable declaration
int a = 0; // corrected ':' to ';'
printf("you've chosen menu A\n");
printf("enter a number\n");
// note
// leading ' ' in format string to consume leading white space
// and no trailing '\n'
if( 1 != scanf(" %d", &a) )
{ // then scanf failed
// handle error condition
perror("scanf failed for number");
exit(EXIT_FAILURE);
}
// implied else, scanf successful
printf("%d\n", a);
}
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
} // end switch
return 0;
} // end function: main

My code repeats more than requried while loop

The problem is that when i type any character except for y or n it display this message two times instead to one)
This program is 'Calculator'
Do you want to continue?
Type 'y' for yes or 'n' for no
invalid input
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main ()
{
//program
//first to get two numbers
//second to get choice
int x=0,y=0,n=0;
char choice;
//clrscr(); does no work in devc++
system("cls"); //you may also use system("clear");
while(x==0)
{
puts("\t\tThis program is 'Calculator'\n\n");
puts("Do you want to continue?");
puts("Type 'y' for yes or 'n' for no ");
scanf("%c",&choice);
x++;
if(choice=='y')
{
y++;
puts("if this worked then we would continue to calculate the 2 no");
}
else if(choice=='n')
exit(0);
else
{
puts("invalid input");
x=0;
}
}
getch();
}
`
it looping twice because enter(\n) character is stored in buffer use scanf like this(add space before %c)
scanf(" %c",&choice);
That is because of the trailing new line after you enter y or n and hit enter key.
Try this out:
scanf("%c",&choice);
while(getchar()!='\n'); // Eats up the trailing newlines
If you input any character other than 'y' or 'n', control enters the :
else
{
puts("invalid input");
x=0;
}
block, which resets x to 0, Now the loop condition :
while(x == 0)
is true and hence it enters the loop again.
Also you may want to skip the trailing newline character while reading like :
scanf(" %c", &choice );

C uninitialized local variable error

New to C still learning.
The program should start the first time with out needing to be asked to do anything. Then it prompts the user to continue with a "Y/N". I keep errors could anyone tell me why it doesn't work I don't know what to do with the errors that I get from it.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
void theQnA(char charIn);
int main(void)
{
int answerint = 0;
char charIn;
char anwser;
printf("Enter a character to be examined: ");
scanf("%c", &charIn);
theQnA(charIn);
while (answerint == 0)
{
printf("Would you like to run it again? Y/N\n");
scanf("%c", &anwser);
if (anwser == 'y')
{
printf("Enter in another character buddy\n");
scanf("%c", &charIn);
theQnA(charIn);
}
else (anwser != 'y')
{
answerint = (answerint--);
}
}
printf("Goodbye\n");
return 0;
}
void theQnA(char charIn)
{
if (islower(charIn))
printf("You have entered in a lower case letter dude\n");
else if (isdigit(charIn))
printf("You enterd in a num man\n");
else if (isupper(charIn))
printf("Its upper case man\n");
else if (ispunct(charIn))
printf("You entered in a punctuation!\n");
else if (isspace(charIn))
printf("You enterd in a whitespace dude\n");
else
printf("control char/n");
return;
}
You have else (anwser != 'y'). It should be else if (anwser != 'y'), or better yet just else. The prompt Would you like to run it again? Y/N will also be printed twice because of how your loop is structured. You have quite a few mistakes, but here's some advice on your loop.
You can use your anwser variable in your while condition. answerint is unnecessary. Also, when you type a character and press enter, scanf (with %c) will extract the character but leave the newline in the buffer. That means the next call to scanf will return a newline, which will make it appear as if your program is skipping your input statements. To fix this, add a space before the %c in your call:
scanf(" %c", &charIn);
Your logic was also a bit out of place. Look at how this example is structured.
printf("Enter a character to be examined: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
while (anwser == 'y')
{
printf("Enter in another character buddy: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
}

I cannot seem to loop again after selecting default in switch case in C

hello guys I coded something like kfc menu,and I got it to work(finally),but when I input something other than numbers for "menu",eg:the letter "A", I just can't get it to loop again to normal,instead it finishes the program
#include <stdio.h>
#include <stdlib.h>
int main()
{
char counter='y';
float totalprice=0;
while (counter=='Y' || counter=='y')
{
int menu;
float price=0;
printf("\nplease select from menu:");
scanf (" %i", &menu);
switch(menu)
{
case 1: {
printf("\none hotbox1 =RM10.50");
totalprice=totalprice+10.50;
break;
}
case 2: {
printf ("\none hotbox2=RM10.60");
totalprice=totalprice+10.60;
break;
}
case 3:{
printf ("\none hotbox3=RM10.70");
totalprice=totalprice+10.70;
break;
}
default : {
printf ("\nplease enter proper number please:");
scanf("%2f", &menu);
break;
}
}
printf("\n\nadd order?(Y/N):");
scanf (" %c", &counter);
}
printf("\n\nThe total price is: %f", totalprice);
return 0;
}
You should use fgets() (reference here) first and then sscanf() (reference here), checking it's return value to see if it's a number.
char inputBuffer[MAX_BUFFER];
do
{
fgets(inputBuffer, MAX_BUFFER, stdin);
}
while(sscanf(inputBuffer, "%d", &menu) != 1)
You scanf with %f in the default case, I am fairly certain that is for floats. Use %d.
Remove scanf("%2f", &menu);
Switch in C does not support char in switch-case. Before you start switch-case validate the user input. If it is a number go into switch case otherwise display a user message to enter only numeric value
I recommend that you debug this by printing out the value of "counter" at various points in the loop (i.e. after you read it in, at the bottom of the loop, etc.). This will give you visibility into what your code is doing.
You can try something like this
#include <stdio.h>
int main()
{
char counter;
float totalprice=0;
int menu=0;
do
{
printf("\n1. one hotbox1=RM10.50");
printf("\n2. one hotbox2=RM10.60");
printf("\n3. one hotbox3=RM10.70");
printf("\nplease select from menu:");
scanf ("%d", &menu);
switch(menu)
{
case 1:
printf("\none hotbox1 =RM10.50");
totalprice=totalprice+10.50;
break;
case 2:
printf ("\none hotbox2=RM10.60");
totalprice=totalprice+10.60;
break;
case 3:
printf ("\none hotbox3=RM10.70");
totalprice=totalprice+10.70;
break;
default :
printf ("\nplease enter proper number please:");
scanf("%d", &menu);
}
printf("\n\nadd more order?(Y/N):");
fflush(stdin); //to empty the input stream.
scanf("%c",&counter);
}while(tolower(counter) != 'n'); //tolower returns the lowercase character.
printf("\n\nThe total price is: %.2f", totalprice);
return 0;
}
When scanf("%i", &menu) tries to read an integer from the input, it finds A, which it cannot interpret as a number, so it does not read it(*). Then the next scanf continues reading the input from when the other left off and happily reads the letter 'A'. Since you loop as long as the read letter is either 'y' or 'Y' (which A is neither), it exits the loop.
(*) read up on the documentation of scanf to see how to tell if it encountered an error.
Note: scanf("%i", &menu) should be scanf("%d", &menu) as%d` is the formatting symbol for integers.
One solution would be to change the loop condition to:
while (counter!='N' && counter!='n')
{
...
}
This way you end the loop only if an explicit 'N' or 'n' is inputted.
Note: it won't help if you accidentally type 'n' for the menu item, so see the comment about the error handling above.

Resources