Logic Error in C Program on xcode - c

I have written this code for a grocery store.. This code makes perfect sense to me. However, I keep getting a logic error. Every time the user enters a bill and then presses -1 to exit, he is taken back to the main menu. When user presses choice 2 to EXIT program, the program is NOT exiting and he taken back to case 1 for some reason. Could you please help me? Thank you!
#include <stdio.h>
int main(void){
double prices[7];
prices[0]=2.55;
prices[1]=12.07;
prices[2]=2.00;
prices[3]=0.55;
prices[4]=5.35;
prices[5]=8.65;
prices[6]=2.55;
int choice;
int productCode;
int quantity;
char stop[3];
int compare;
double price;
double totalPrice=0;
do{
printf("\n1. Create new bill");
printf("\n2. EXIT");
printf("\n\nEnter choice: ");
choice=scanf("%d", &choice);
switch(choice){
case 1:{
do{
printf("\nEnter product code: ");
scanf("%d",&productCode);
printf("\nEnter quantity of product: ");
scanf("%d",&quantity);
price=prices[productCode]*quantity;
totalPrice=totalPrice+price;
printf("\nTo stop entering products enter -1.. to continue press any other character ");
scanf("%s", &stop);
compare=strcmp(stop, "-1");
}while(compare!=0);
break;
}
case 2: break;
default: printf("\nInvalid choice");
}
}while(choice!=2);
getchar();
return 0;
}

Instead of
choice=scanf("%d", &choice);
Do
scanf("%d", &choice);
scanf return value is:
On success, the function returns the number of items of the argument
list successfully filled. This count can match the expected number of
items or be less (even zero) due to a matching failure, a reading
error, or the reach of the end-of-file.
If a reading error happens or the end-of-file is reached while
reading, the proper indicator is set (feof or ferror). And, if either
happens before any data could be successfully read, EOF is returned.
If an encoding error happens interpreting wide characters, the
function sets errno to EILSEQ.
http://www.cplusplus.com/reference/cstdio/scanf/
for (;;){
printf("\n1. Create new bill");
printf("\n2. EXIT");
printf("\n\nEnter choice: ");
scanf("%d", &choice);
if(choice == 2 ){
break;
} else if(choice == 1){
do{
printf("\nEnter product code: ");
scanf("%d",&productCode);
printf("\nEnter quantity of product: ");
scanf("%d",&quantity);
price=prices[productCode]*quantity;
totalPrice=totalPrice+price;
printf("\nTo stop entering products enter -1.. to continue press any other character ");
scanf("%s", &stop);
compare=strcmp(stop, "-1");
}while(compare!=0);
} else {
printf("\nInvalid choice");
}
}

Related

I'm trying to make a menu in C and my code is not working the way I want it to

I'm working on an assignment for my programming class and the first thing I tackled is of course to make the main menu. But for some reason, the program is not working the way I intend it to.
#include <stdio.h>
#include <stdlib.h>
void mainMenu();
void firstChoice();
int main()
{
int main_menu_choice;
int _1returnMenu;
mainMenu();
scanf("%d", &main_menu_choice);
while (main_menu_choice != 0){
switch(main_menu_choice){
case 1:
firstChoice();
scanf("%d", &_1returnMenu);
while (_1returnMenu != 0){
switch (_1returnMenu){
case 1:
firstChoice();
scanf("%d", &_1returnMenu);
break;
case 0:
mainMenu();
scanf("%d", &main_menu_choice);
break;
default:
printf("Invalid option, please try again: \n");
scanf("%d", &_1returnMenu);
break;
}
}
break;
case 0:
exit(0);
default:
printf("Invalid option, please try again: \n");
scanf("%d", &main_menu_choice);
}
}
return 0;
}
void firstChoice(){
printf("Enter the necessary information \n");
printf("Please enter the student's ID: \n");
scanf("%d", &student.id);
printf("Please enter the student's name: \n");
scanf("%s", student.name);
printf("Please enter the gender of the student: \n");
scanf("%s", student.gender);
printf("Please enter the details of the room: \n");
scanf("%s", student.roomDetails);
printf("Please enter the amount due of the student: \n");
scanf("%d", &student.amountDue);
printf("Please enter the amount paid by the student: \n");
scanf("%d", &student.paymentMade);
printf("Do you want to store another hosteler's information? \n");
printf("Type 1 if you wish to continue, Type 0 to go back to the main menu: \n");
return;
}
void mainMenu(){
printf("Welcome! This program will help you in managing the hostel booking
of Wisdom College \n");
printf("Type the number of your option: \n");
printf("1. Store details of hosteler \n");
printf("2. Check room availability \n");
printf("3. Payment Facility \n");
printf("4. Search room details of hosteler \n");
printf("5. To cancel booking of a hosteler \n");
printf("6. Change room type \n");
printf("0. Exit the program \n");
return;
}
Okay so when I run the program and I choose the first option which is "1.Store details of hosteler" then just put on some random information and after inputting the required info the program will ask me if I want to continue using it or not. If I press 1 it will ask me to fill up the required information again and if I press 0 it should go back to the main menu.
But the thing is, when I type in 0 it doesn't go back to the main menu, instead it just runs the firstChoice() function again instead of running the case 0 in the switch statement. I've been scratching my head for 2 hours trying to figure out what's wrong but I just cant seem to find what's wrong. I'm so sorry if I wasn't able to word my problem properly, and thanks in advance!
the following proposed code shows how to write the menu display and handling
int done = 0;
while( !done )
{
mainMenu();
if( scanf("%d", &main_menu_choice) != 1 )
{
fprintf( stderr, "scanf for menu choice failed\n" );
exit( EXIT_FAILURE );
}
switch(main_menu_choice)
{
case 0:
done = 1;
break;
case 1:
firstChoice();
break;
case 2:
checkRoomAvalability();
break;
case 3:
paymentFacility();
break;
case 4:
switchRoomDetails();
break;
case 5:
cancelBooking();
break;
case 6:
changeRoomType();
break;
default:
puts("Invalid option, please try again: \n");
break;
}
}
void mainMenu()
{
puts( "Welcome!"
" This program will help you in managing"
" the hostel booking of Wisdom College \n"
"Type the number of your option: \n"
"1. Store details of hosteler \n"
"2. Check room availability \n"
"3. Payment Facility \n"
"4. Search room details of hosteler \n"
"5. To cancel booking of a hosteler \n"
"6. Change room type \n"
"0. Exit the program \n" );
}

I need my program to tell the user "invalid entry..." if they dont input a correct variable type

The issue im having is when the user is prompted to enter a value if an invalid option is entered that is not of the type im scanning for i need the program to display a message "invalid entry" and break.
if (UserInputTri == 'A')
{
system("cls");
TriPermTotal = 0;
printf("\nYou chose to calculate perimeter.\n\nPlease enter a value for side number 1: ");
scanf("%f", &TriPerm1);
printf("Please enter a value for side number 2: ");
scanf("%f", &TriPerm2);
printf("Please enter a value for side number 3: ");
scanf("%f", &TriPerm3);
TriPermTotal = TriPerm1 + TriPerm1 + TriPerm3;
printf("\nThe total perimeter of the triangle is: %0.0f\n\n", TriPermTotal);
system("pause");
system("cls");
break;
else
{
printf("\nNot a valid option, try again!\n\n");
system("pause");
system("cls");
break;
}
If I type in a word instead of a number when the user is asked for side 1 it will loop forever.

How do I get my code from going into an infinte loop?

I am rewriting the Guessing Game code from 'C Programming for Absoulute Beginners' to verify that the user has entered in a digit, using the isdigit() function.
The rest of the code works, in terms of error checking; but the moment that the user enters in a non-digit, the code goes into an infinite loop.
#include <stdio.h>
#include <stdlib.h>
#define NO 2
#define YES 1
main()
{
int guessGame;
guessGame = 0;
int iRandomNum = 0;
int iResponse = 0;
printf("\n\nWould you like to play \"The Guessing Game\"?\n\n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
do{
if(guessGame == YES){
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10:\n\n ");
scanf("%d", &iResponse);
if(!isdigit(iResponse)){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
if(iResponse == iRandomNum){
printf("\nYou guessed right\n");
printf("\nThe correct guess is %d!\n", iRandomNum);
printf("\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
} else {
printf("\n\nSorry, you guessed wrong\n");
printf("\nThe correct guess was %d!\n", iRandomNum);
printf("\n\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
}
}
else {
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
scanf("%d", &iResponse);
}
}
else {
printf("\nThe window will now close. Try again later!\n");
exit(0);
}
}while(guessGame != NO);
}
The code goes into infinite loop as scanf() is unable to read an integer. The character you entered remains in the keyboard buffer.No more reading of integers is possible as long as the character is present in the buffer. scanf() simply returns the number of items read as 0 each time. Hence,the program does not wait for the user to enter data and infinite loop results.
scanf() returns number of items successfully read. So,you can simply check for the return value of scanf(), if its 1 then scanf() has correctly read an integer.
check = scanf("%d", &iResponse);
if(check == 1){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
and flush the buffer if wrong input is entered
else {
while (getchar() != '\n'); //flush the buffer
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
//scanf("%d", &iResponse);
}
no need to ask for input here, while loop will continue and prompt for input in the beginning
Trying taking the input in the form of string .. also u will have to compare the input in the form 'number' :)

How to make getchar() read a negative number?

I am writing a program that can calculate the areas of a square, cube, and circle. The program needs to present an error message and allow the user to enter a new choice if they enter something not included in the menu. My problem is that if they type anything includes my menu options then the program still executes. (i.e. -1, 23, 344) I was wondering how to get it to ignore anything after the first character or to read the whole string. Or if there is something better than getchar(). I'm open to any solutions! Thank you!
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int choice;
int lengthsq;
int areasq;
int lengthcube;
int areacube;
int radius;
double circlearea;
printf("Area Calculation\n");
printf("(1) Square\n");
printf("(2) Cube\n");
printf("(3) Circle\n");
fputs("Please make a selction: ", stdout);
while((choice = getchar()) != '\n')
switch (choice) {
case '1':
printf("\nPlease enter the length: ");
scanf("%d", &lengthsq);
while(lengthsq <= 0){
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthsq);
}
areasq = lengthsq * lengthsq;
printf("The area of the square is %d.", areasq);
return 0;
case '2':
printf("\nPlease enter the length: ");
scanf("%d", &lengthcube);
while (lengthcube <= 0) {
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthcube);
}
areacube = 6 * lengthcube * lengthcube;
printf("The surface area of the cube is %d.\n", areacube);
return 0;
case '3':
printf("\nPlease enter the radius: ");
scanf("%d", &radius);
while(radius <= 0){
printf("Error! Pleae enter a postive number: ");
scanf("%d", &radius);
}
circlearea = 3.14159 * radius * radius;
printf("The area of the circle is %.2f.\n", circlearea);
return 0;
case '\n':
case '\t':
case ' ':
break;
default:
printf("\nInvalid choice entered.\n");
fputs("Enter a new choice: ", stdout);
break;
}
}
You could add another switch case for the dash, which would toggle some kind of negative flag and then read a number as you're already doing. If you do not like introducing such a flag, then the best option would be using fgets, which returns the entire input line. But that has the downside that you need to parse the input. I.e. do some string manipulation, which may be slightly more complex than a simple flag parameter.
On the other hand, from the code you attached, I deduct that the only valid input consists of mere numbers (integers). You could just read an integer then with scanf.

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