Main Menu choice prompt is gathered even on sub Function scanf (C) - c

Im creating a program that has a Main Menu linked to a couple of other functions. This is the Main Menu Code
int main(){
int iMenuChoice,exit;
iMenuChoice=0;
exit =1;
while (exit !=0){
system("cls");
printf("**********Main Menu************\n");
printf("*1) Cartesian Plane *\n");
printf("*2) Number to Words *\n");
printf("*3) b *\n");
printf("*4) c *\n");
printf("*5) d *\n");
printf("*6) e *\n");
printf("*7) Exit *\n");
printf("*******************************\n");
scanf("%d",&iMenuChoice);
switch (iMenuChoice) {
case 1:
Cartisian();
break;
case 2:
Num2Word();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
system("cls");
printf("\n\nThank you for using our Program\n\n ");
exit = 0;
break;
default:
break;
}
}
getche();
}
So I test my Number to words function which prompts for a User input (Int).
But when I enter the number, The function will ask for another number (no printf prompt just a _ that waits for a number input), Lets call this mystery number X.
After the function is done converting the number, The Program will go to main menu for a split second and automatically goes to another function.
I realized that The mystery number X is somehow being used as an advance menu input! I dont know what i did wrong.
Here is the code for The num2Word function.
int Num2Word()
{
int iWor,iOnes,iTens,iHundred,iThousand;
system("cls");
printf("Enter a number(max 3000)\n");
scanf("%i \n",&iWor);
if(iWor<=3001)
{
iOnes=iWor%10;
iWor=iWor/10;
iTens=iWor%10;
iWor=iWor/10;
iHundred=iWor%10;
iWor=iWor/10;
iThousand=iWor%10;
Thousand(iThousand);
Hundred(iHundred);
if(iTens!=1)
{
Tenty(iTens);
Ones(iOnes);
}
if(iTens==1)
Exception(iOnes);
}
else{
printf("beyond 3000");
}
getche();
return 0;
}
The Tenty,Ones, Hundredth and Thousandths all use Switch, same structure as code below:
int Ones(int x)
{
if(x!=0){
switch(x)
{
case 1:
printf("One");
break;
case 2:
printf("Two");
break;
case 3:
printf("Three");
break;
case 4:
printf("Four ");
break;
case 5:
printf("Five");
break;
case 6:
printf("Six");
break;
case 7:
printf("Seven");
break;
case 8:
printf("Eight");
break;
case 9:
printf("Nine");
break;
default:
break;
}
}
return;
}
Since I cant post images yet ill try to show how the function output looks like
Enter a Number (Max 3000):
619
//I press enter here and nothing happens
3 //I must input another number for it to show the conversion, in this case number 3.
six hundred nineteen
After this, itll go back to main menu for a split sec and go straight to Main() Switch(iMenuChoice) Case 3.

There's no mystery number X or ghost :)
Change
scanf("%i \n",&iWor);
to
scanf("%i",&iWor);
The whitespace characters you have in the format string of scanf, ignores all whitespace characters. That's why you are forced to input a non-whitespace character.

I realized that The mystery number X is somehow being used as an
advance menu input! I dont know what i did wrong.
There is no mystery number X. The problem in your code is this line:
scanf("%i \n",&iWor);
This scanf ignores white-space characters. When a white-space character is specified as directive in scanf. This directive maches any amount of white space, including none, in the input. That's why you have to insert the second "mysterious" value. According to scanf documentation a white space character is a sequence of white-space characters (space, tab, newline etc.; see isspace(3)).
To solve the issue, you can just %i directive. For example:
scanf("%i",&iWor);
Docs: http://man7.org/linux/man-pages/man3/scanf.3.html

Related

Need insight with grading in C using switch, and case tags [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 21 days ago.
Improve this question
printf("On a scale of (A - F) rate your experience with our Consortium's HR Department\n\n");
char Grading;
printf("\nEnter a grade: \n\n");
scanf("%c", &rate);
switch (Grading) {
case 'A':
printf("Perfect!\n\n");
break;
case 'B':
printf("You did good!\n\n");
break;
case 'C':
printf("You did okay\n\n");
break;
case 'D':
printf("At least not bad\n\n");
break;
case 'E':
printf("Bad\n\n");
break;
case 'F':
printf("Awful\n\n");
break;
default:
printf("Please enter only valid grades\n\n");
}
return 0;
}
This is just the section i need help with in my codeblocks. Doing this separately on a different visual studio tab works, but together with my previous codes;it keeps saying enter only valid grades
I tried making a grading on C. My code actually works, i mean that exact grading code block works on a different tab. But when added to my previous code, the project ima working on, it keeps saying enter only valid grades. Ima kinda asking if there's a finna conventional method of adding the C grading block to a project in C
In your switch statement you are checking the value of Grading, but scanf writes its output in rate.
You should change your switch case like so:
printf("On a scale of (A - F) rate your experience with our Consortium's HR Department\n\n");
char rate; //rename Grading to rate
printf("\nEnter a grade: \n\n");
scanf("%c", &rate);
switch (rate) { //rename Grading to rate
case 'A':
printf("Perfect!\n\n");
break;
case 'B':
printf("You did good!\n\n");
break;
case 'C':
printf("You did okay\n\n");
break;
case 'D':
printf("At least not bad\n\n");
break;
case 'E':
printf("Bad\n\n");
break;
case 'F':
printf("Awful\n\n");
break;
default:
printf("Please enter only valid grades\n\n");
}
return 0;
}
Use &Grading instead of &rate
Or
Declare char rate instead of Grading
You have declared Grading and scanf uses rate

When trying to output an integer, to a file it outputs an array of numbers

I'm writing a function that will give the user an option to choose an item from a list.
When an option is chosen it should then call a dedicated function to ask for the quantity of the item and then output it to a file. Below are the two functions.
void pos2()
{
int choice;
printf("\n Enter The item : ");
scanf("%d", &choice);
switch (choice) {
case 1:
apple();
break;
case 2:
editInventory();
break;
case 3:
printf("\n Returning... \n\n");
printf("Returning in 3 seconds...\n");
Sleep(3000);
system("cls");
printMenu();
default:
system("cls");
printf("\ninvalid choice Try again \n");
printMenu();
}
}
void apple()
{
FILE*out=fopen("pos.txt","w");
int amt;
printf("Apple Choosen\n");
printf("Enter the Amount\n");
scanf("%d",&amt);
fprintf(out,"%d",&amt);
}
In this case, the user is only able to choose 1 at the moment which will ask them to enter the number of apples, and then enter, it would save the value to a text file called pos.txt. When I do enter an amount it appears I'm given the address value or some sort of array in return. This is the output in the text file:
6421716
if anyone can offer assistance or guide me in the right direction that would be appreciated. Thanks in Advance
Great News, #Passerby (https://stackoverflow.com/users/17196203/passerby) commented the solution under my Question.
The issue here was the & in my fprintf(out,"%d",&amt); which was causing the weird number to be outputted. Thanks once again to everyone helping me solve this and a special thanks to #Passerby for the solution.

Can this if be added to this switch statement?

Hi so I'm building a hotel management program and I'm trying to make my switch statement short but it's not working. I tried to add a function that had the break inside but I get an error saying break not within a loop or a switch statement:
void goback()
{
char y;
printf("Would you like to go back?(Y/N)");
scanf("%c",&y);
if (y=='Y' || y=='y')
{
break;
}
}
int main(){
do
{
printf (" 1. Add a Room\n 2. Current rooms\n 3. Add a booking\n 4. Current bookings \n 5. Modify a booking\n 6. Print bill\n 7. Exit\n\n");
printf ("Which section would you like to access:");
scanf ("%d",&w);
switch (w){
case 1:
clrscr();
newroom();
goback();
case 2:
clrscr();
roomscan();
goback();
case 3:
clrscr();
addbooking();
goback();
case 4:
clrscr();
currentbooking();
goback();
case 5:
clrscr();
printf("not ready\n");
case 6:
clrscr();
printf("not ready\n");
case 7:
clrscr();
printf("\t\t\t\tLogging out... See you next time!");
exit (1);
break;
default:
printf("try again");
}
}
while (w!=7);
}
of course, you got an error because of the break; statement break you from your goback() function and not from case.
As you know each case block must end with break;.
In your case, you must put the break; statement at the end of each case block and you can make the goback() function returning a boolean to decide if you go back or not, but you must define what to do if the user does not want to go back.
I'm not sure but you might want to add breaks after your statements if they are to be executed separately and not in sequence. here I only see your case 7 contains a break, which means all cases until that one will be executed, if that's what you want it's fine, otherwise maybe try something like this
switch (w){
case 1:
clrscr();
newroom();
goback();
break;
case 2:
clrscr();
roomscan();
goback();
break;
case 3:
...
Here it seems that your goback() function tries to do that break but what it does it's it tries to break from the context where it if called, here an "if" bloc, which can't have a break inside it. That's what the compiler is saying I guess.

Switch Statement with three cases in C. Third Case is not running properly

below is a do-while loop that I coded. When I run it, the first two cases do their job and run perfectly. However. the third case is supposed to quit the program but instead it does nothing and just goes back to the series of printf statements in the beginning of the do-while loop. Any suggestions as to what I am doing wrong?
do
{
printf("Choose one of the following (1, 2, or 3) \n");
printf("1. Find GCD of two positive integers\n");
printf("2. Sort 3 integers in the ascending order\n");
printf("3. Quit the program\n");
printf("Please enter your choice: ");
scanf("%d", &option);
switch (option)
{
case 1:
gcd(p, q);
printf("\nDo you want to try again? Say Y(es) or N(o): ");
getchar();
response = getchar();
break;
case 2:
sort(p, q, r);
printf("\nDo you want to try again? Say Y(es) or N(o): ");
getchar();
response = getchar();
break;
case 3:
break;
}
}
while (response == 'Y' || response == 'y'); //Condition that will determine whether or not the loop continues to run.
printf("\nThank you for using my progam. Goodbye!\n\n");
return 0;
}
Response variable remains either Y or y and while loop never exits.
add
response = 'x'; //or something that isn't Y or y
before break; in case 3: option.
break statement exits from first iterative loop. In your case this is switch.
You must modify the response ( for example response =0).
case 3:
response=0; //different than 'Y' or 'y'
break;
Do it like this:
case 3:
return 0;
You also might consider eliminating case 3 and just do this:
default:
return 0;
in case 3,there is no input coming from the user, so the response variable remains true, try asking the user for an input or just put response = '(any letter that will make the condition false)'
break statement does not exit the program, it just exits from the switch block.
To exit :
1.
#include<stdlib.h>
And instead of break statement, use exit(0);
2.Change the case 3 as follows:
response='N';break;
The break statement in case 3 just exits from case 3 rather than from the program.
If you want to exit the program in case 3 then use the return statement.
return 0;
This statement exists the program rather than repeating the while loop.
You just interrupt the switch case.
How about using:
case 3:
return;
break;

Programming in C. Data validation and converting characters into integers

I am making a program that includes a simple switch condition.
The problem I have encountered is that I am also validating user input so that the user cannot break the program by entering a character.
The switch works fine when I remove the isdigit() so I know it is something happening with data validation.
What I was told to do was use %c in my scanf() but if I do that then something else prevents the program from working. I suspect that it is because the switch is no longer is being referenced since the cases are 1,2,3...
The way I want to do it is just turn the character back into an integer before it reaches the switch but I am not sure how I could do that.
Something is happening when I copy and paste parts of the program so I will just paste the entire program.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int BusRoute, LTrigger;
char StartLoc,DestLoc;
LTrigger = 1;
BusRoute = 0;
StartLoc = 0;
DestLoc = 0;
while (LTrigger >= 1)
{
//Give user a menu and prompt to select input for BusRoute
printf("\n\n\tPlease only use the numbers provided.");
printf("\n\n 1.\n\tRoute_1\tCherokee Park and KFC YUM Center transit.");
printf("\n\n 2.\n\tRoute_2\tUL and Cherokee Park transit.");
printf("\n\n 3.\n\tRoute_3\tUL and KFC YUM Center transit.");
printf("\n\n\n\t Please select one route from the above menu.");
printf(" \n\n\tOnly use the single digit corresponding to the route: ");
scanf("%d" , &BusRoute);
//Refresh window
system("cls");
if(isdigit(BusRoute))
{
//Use switch to determin user's Route. Then present choice of To/From
switch (BusRoute)
{
case 1:
printf("\n\n\tYou have chosen Cherokee Park and KFC YUM Center transit.");
printf("\n\n\tIf you want to travel from Cherokee Park to KFC YUM Center enter C.");
printf("\n\n\tIf you want to travel from KFC YUM Center to Cherokee Park enter K.");
printf("\n\n\tEnter your seletion now: ");
scanf("%c" , &StartLoc);
break;
//give two if statements to determine users location and confirm destination
if (StartLoc == 'c' || StartLoc == 'C')
{
printf("\n\n\tYou have chosen to travel from Cherokee Park to KFC YUM Center.");
printf("\n\n\tTo confirm you want to travel from Cherokee Park to KFC YUM Center please enter K: ");
scanf("%c" , DestLoc);
//refresh
system("cls");
//confirmation of destination
if (DestLoc == 'k' || DestLoc == 'K')
{
printf("\n\n\tYour bus route will pick you up from Cherokee Park and take you to KFC YUM Center.");
getch();
}//end dest
}//end start
//false user input
else
{
printf("\n\n\tYou did not enter a correct character.\n\n\tPress enter and only enter specific values.");
getch();
//reset loop and refresh
LTrigger = 1;
system("cls");
}//end else
case 2:
printf("\n\n\tYou have chosen Cherokee Park and UL transit.");
break;
case 3:
printf("\n\n\tYou have chosen UL and KFC YUM Center transit.");
break;
}//end switch
}//end if
else
{
printf("\n\n\tYou did not enter a number.\n\n\tPress enter and only enter specific values.");
getch();
//reset loop and refresh
LTrigger = 1;
system("cls");
}//end else
}//end loop
getch();
}//end main
isdigit takes a character and says if it is a character between '0' and '9'. But you are passing it an integer, not a character, so its output is meaningless.
If you want to know if the scanf succeeded, just check its return value: it will be 1 if it worked, or 0 if it failed (actually it will return the number of variables assigned):
if (scanf("%d", &BusRoute) > 0)
{
If you want to know if BusRoute is one digit long, then you can simply check it to be between 0 and 9 (or 3), but there is no need to do that: instead, add a default: clause to your switch.
BTW, you have missed a & in the line
scanf("%c" , DestLoc);
It should be:
scanf("%c" , &DestLoc);
Also, it is usually a good idea to add a space before the %c it will eat out any space or carriage return left in the buffer (from the previous user operation, for instance):
scanf(" %c" , &DestLoc);
Ditto, for the StartLoc case.
It's tricky to answer this without seeing your code. You can turn a character into an integer with a typecast:
switch((int) variable)
If variable is a character entered by the user, the typecast (int) will convert it to its ASCII code for the switch. Usually, though, C doesn't require typecasts to interpret characters as integers.
Look At this:
char charBusRoute;
int BusRoute;
/* ... */
scanf("%c",&charBusRoute);
if(isdigit(charBusRoute)){
BusRoute = charBusRoute - '0';
/* ... */
}

Resources