I'm a beginner in C program, and I'm trying to make a restaurant order menu.
I start with user input "Y" to start order.
Then I want the program to keep taking orders until user input "N" to stop.
When input "N", the total sales will printed.
But I cannot do the looping, would you mind to help me? Thank you. :)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int code;
float totalPrice=0, totalSales = 0 ;
char choice, choice1;
printf("Welcome to Deli Sandwich! Enter Y to start your order!\n");
scanf("%c", &choice);
while(choice=='Y'|| choice=='y')
{
printf("\n____________________________SANDWICH FILLING______________________________\n");
printf("\n\t\t Menu \t\t Code \t\t Price\n");
printf("\n\t\t Egg \t\t 1 \t\t RM 1.00\n");
printf("\n\t\t Tuna \t\t 2 \t\t RM 2.00\n");
printf("\n\t\t Seafood \t 3 \t\t RM 3.00\n");
printf("\n\t\t Chicken Ham \t 4 \t\t RM 2.50\n");
printf("\nSandwich Filling code: ");
scanf("%d", &code);
switch(code)
{
case 1:
printf("Egg is picked.\n");
totalPrice+= 1;
break;
case 2:
printf("Tuna is picked.\n");
totalPrice+= 2;
break;
case 3:
printf("Seafood is picked.\n");
totalPrice+= 3;
break;
case 4:
printf("Chicken Ham is picked.\n");
totalPrice+= 2.50;
break;
default :
printf("invalid code.");
}
printf("\n_____________________________SANDWICH TYPE________________________________\n");
printf("\n\t\t Menu \t\t Code \t\t Price\n");
printf("\n\t\t Half \t\t 1 \t\t RM 3.00\n");
printf("\n\t\t Whole \t\t 2 \t\t RM 5.00\n");
printf("\nSandwich Type code: ");
scanf("%d", &code);
switch(code)
{
case 1:
printf("Half is picked.\n");
totalPrice+= 3;
break;
case 2:
printf("Whole is picked.\n");
totalPrice+= 5;
break;
default :
printf("invalid code.");
}
printf("\nThe total price is RM%.2f.\n", totalPrice);
printf("Thank You. Please come again!\n");
totalSales+= totalPrice;
printf("\nWelcome to Deli Sandwich! Enter Y to start your order!\n");
scanf("%c", &choice);
}
printf("\nThe total sales is RM%.2f.\n", totalSales);
return 0;
}
Thank you again :)
Change
scanf("%c", &choice);
to
scanf(" %c", &choice); // note the space before %c
This is done to discard all white-space characters like \n and spaces from the stdin.
When you enter data for a scanf,you enter some data and press the enter key. scanf consumes the data entered and leaves the \n(enter key) in the input buffer(stdin). When scanf with a %c is called the next time, it will take the \n as input(left over by the previous scanf) and will not wait for further input.
In your code,
scanf("%c", &choice);
before the while loop consumes the character you entered and leaves the \n in the stdin. As for why
scanf("%d", &code);
waits for input is that the %d format specifier skips white-space characters while %c does not.
scanf(" %c", &choice);
Ignore the newline character at the end of the input by placing a space before %c
simple add the space before %c
The ENTER key press after providing the input is stored into the input buffer stdin and considered a valid input for %c format specifier for the recurring scanf()s. To avoid scanning the stored \n, you need to change your code like
scanf(" %c", &choice);
^
|
This leading space indicates to ignore any leading whitespace or whitespace-like characters (including \n) and scan the first non-whitespace character. [In your case y/ Y/ n...]
Related
Hi I am new to programming and I got a trouble when I try to make a little change to the example in the book.
/* Chapter 3 Example, C Prime Plus */
#include <stdio.h>
int main(void)
{
char Letter, ch;
int intValue;
printf("Please enter a letter: \n");
scanf("%c", &Letter); /* user inputs character */
printf("The code for %c is %d.\n", Letter, Letter);
printf("Now is another we to implement the process: \n");
printf("RN, the value of ch is %c, and the value of intValue is %d\n", ch, intValue);
printf("Please enter a letter: \n");
scanf("%c", &ch);
intValue = ch;
printf("The code for %c is %d.\n", ch, intValue);
return 0;
}
When I run it, the outcome would be
Please enter a letter:
M
The code for M is 77.
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10.
and the part
"
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10. " will all come out without asking me to enter a value.
I want to know why and are there any other way to implement it that is different from examples in the book?
Thank you for your time!
Hi Matt_C and welcome to SO.
First, you don't need the second bloc of printfs and the scanf, it just trying to do the same thing and there is an order error.
Second, it is tricky when you try consecutive scanf, it holds the last key pressed (enter is the last key pressed = \n). This is why it skips the second scanf.
There a little solution for that, add a space at the beginning of the scanfs. Try this:
int main() {
char exit, letter;
while (1) {
printf("Please enter a letter: ");
scanf(" %c", &letter);
printf("\nThe code for '%c' is %d. \n\n", letter, letter);
printf("Exit ? (y/n): ");
scanf(" %c", &exit);
if(exit == 'y')
{
break;
}
system("clear"); // UNIX
//system("cls"); // DOS
}
}
Don't forget to choose one answer that you believe is the best solution to your problem.
I am creating a calculator file in C with a while loop and a switch statement. The first time through the while loop, everything works fine, but when it goes through the second time, the my printf gets called before I have the opportunity to enter the data into the preceding scanf.
I have tried using '\n' before the text in the printf and I have also tried using fflush(stdout) before and after the scanf call.
Current output:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: Enter both numbers in required sequence:
What I want:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: // then I can enter a new choice for the switch //
The code I've tried:
while(input != 'q'){
printf("Welcome to the Calculator\nOperation choices:\tAddition(A)\n\t\t\tSubtraction(S)\n\t\t\tMultiplication(M)\n\t\t\tDivision(D)\nEnter choice: ");
fflush(stdout);
scanf("%c", &input);
fflush(stdout);
printf("\nEnter both numbers in required sequence: ");
scanf("%f %f", &num1, &num2);
switch(input){
case 'A':
result = num1 + num2;
break;
case 'S':
result = num1 - num2;
break;
case 'M':
result = num1 * num2;
break;
case 'D':
result = num1 / num2;
break;
default:
printf("Please choose a valid operation.");
break;
}
if(result > 100){
printf("Greater than 100.\n");
}
else if(result < 100) {
printf("Less than 100.\n");
}
else{
printf("Equal to 100.\n");
}
}
printf("Quit the menu.\n");
return(0);
}
The sequence of events in you program is correct, what happens is that scanf() reads a lingering '\n' new line character that is left in the stdin buffer from a previous input. The '\n' is consumed by scanf() and the program continues the execution.
You will need to clear the buffer before scanf() is executed.
Option 1 - Clear the buffer at the bottom of the while cycle:
//...
int c;
//...
else{
printf("Equal to 100.\n");
}
while((c = fgetc(stdin)) != '\n' && c != EOF){}
//...
Option 2 (simpler) - Use a space before %c specifier:
scanf(" %c", &input);
^
Try this : scanf(" %c", &input); (add space before %c)
scanf will likely take \n in buffer as input and placed in you character input.
This question already has answers here:
program wont read at second scanf()
(2 answers)
Closed 2 years ago.
I am making a mini project i c with the help of nested switch statement in my code Error is in 15th line of the code,here %c is not working but %s is working,please help me to solve this query and tell me how to run this code with the use of %c here is my code:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,ch;
char choice;
clrscr();
printf("1.Calculator\n2.Convrter\n\n");
printf("Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("1.Addition(A)\n2.Subtraction(S)\n3.Multiplication(M)\n4.Division(D)\n5.Module(P)\n\n");
printf("Enter your choice : ");
**scanf("%c",&choice);**
switch(choice)
{
case 'A':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a+b;
printf("%d",c);
break;
case 'S':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a-b;
printf("%d",c);
break;
case 'M':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a*b;
printf("%d",c);
break;
case 'D':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a/b;
printf("%d",c);
break;
case 'P':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a%b;
printf("%d",c);
break;
default:printf("Invalid Input");
}
break;
}
getch();
}
you just need to add getchar(); before
scanf()
because you will take \n as char choice
so one getchar will solve your problem
case 1:printf("1.Addition(A)\n2.Subtraction(S)\n3.Multiplication(M)\n4.Division(D)\n5.Module(P)\n\n");
printf("Enter your choice : ");
getchar();
scanf("%c", &choice);
switch (choice)
%s will work because it takes more than one char.
or you can:
1:printf("1.Addition(A)\n2.Subtraction(S)\n3.Multiplication(M)\n4.Division(D)\n5.Module(P)\n\n");
printf("Enter your choice : ");
scanf(" %c", &choice); //add space before %c
switch (choice)
as H.S. said in comment.
The previous call to scanf():
scanf("%d",&ch);
in Line 10, leaves the newline character (\n) made by the push to Enter/Return inside stdin.
This newline character is read on the second scanf() call since the %c format/conversion specifier does not ignore leading white space and also read/consumes non-printable characters.
Just insert white space before the conversion specifier %c:
scanf(" %c",&choice);
to catch that newline character or any leading white space.
I am creating a little scoring program and am having trouble with this case. When I enter an 'e', it breaks correctly as the default suggests, but then it runs through the first switch statement, and then exits the program..
This only happens when I enter the letter 'e'. If i enter 'q' or anything else, it doesnt exit ?
case 'd': // Field Competition Logs
{
int fieldRound;
int ifaaField[2], ifaaFieldTotal;
int ifaaHunter[2], ifaaHunterTotal;
int fitaField[1];
int field3D[1];
printf ("Please select the type of round you shot\n\n");
printf ("\t(a) IFAA Field\n\t(b) IFAA Hunter\n\t(c) Fita Field\n\t(d) 3D Field\n> ");
scanf (" %d", &fieldRound);
switch (fieldRound)
{
case 'a': // Ifaa Field Round
{
printf ("Please enter the score for your first round > ");
scanf (" %d", &ifaaField[0]);
printf ("Please enter the score for your second round > ");
scanf (" %d", &ifaaField[1]);
ifaaFieldTotal = ifaaField[0] + ifaaField[1];
printf ("Total of your first half (%d) and your second half (%d) is %d", ifaaField[0], ifaaField[1], ifaaFieldTotal);
break;
}
case 'b': // Ifaa Hunter Round
{
printf ("Please enter the score for your first round > ");
scanf (" %d", &ifaaHunter[0]);
printf ("Please enter the score for your second round > ");
scanf (" %d", &ifaaHunter[1]);
ifaaHunterTotal = ifaaHunter[0] + ifaaHunter[1];
printf ("Total of your first half (%d) and your second half (%d) is %d", ifaaHunter[0], ifaaHunter[1], ifaaHunterTotal);
break;
}
case 'c': // Fita Field Round
{
printf ("Please enter your Fita Field score > ");
scanf (" %d", &fitaField[0]);
printf ("Total of your Fita Field round is %d", fitaField[0]);
break;
}
case 'd': // Field 3D Round
{
printf ("Please enter your 3D Field score > ");
scanf (" %d", &field3D[0]);
printf ("Total of your 3D Field round is %d", field3D[0]);
break;
}
default:
printf ("Please enter a valid response");
break;
}
break; // Breaks out of Case D
}
case 'e': // Exits the program
{
printf ("Thank you, Good bye!\n");
return 0;
}
OUTPUT
Please select the type of round you shot
(a) IFAA Field
(b) IFAA Hunter
(c) Fita Field
(d) 3D Field
> e
Please enter a valid response
Hi s. c, Please choose from the following options by typing the letter and pressing the 'return' key
(a) Enter Scored Practice logs
(b) Enter Practice Arrow count
(c) Enter Competition logs
(d) Enter Field Competition Logs
(e) Exit Program
> Thank you, Good bye!
scanf (" %d", &fieldRound);
This scanf fails! It expects numeric input, not an alphabetic character!
Change
scanf (" %d", &fieldRound);
to
scanf (" %c", &fieldRound);
In your current configuration, your scanf expects a decimal number, not a character. It thusly fails if you try inputting a character.
Additionally, you need to change int fieldRound; to char fieldRound;.
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.