Creating a Menu with c - c-preprocessor

I am trying to create a menu and my menu is listed a-d. I want the if statement to read a for first item in menu all the way to do but my program keeps crashing. How can I fix this?
#include <stdio.h>
#include <string.h>
int main()
{
char option[4];
system("cls");
printf("+++++++++++++++++++++++++++++++++++++>>>ATHLETE DATA MANAGEMENT SYSTEM<<<++++++++++++++++++++++++++++++++++++++\n\n");
printf("\t\t\t\t\ta\. Enter Athlete Data\n");
printf("\t\t\t\t\tb\. Determine Distance to Reach World Record\n");
printf("\t\t\t\t\tc\. Display Athlete Management Report\n");
printf("\t\t\t\t\td\. Exit\n");
printf("Type the corresponding letter (a-d) to access the menu. ");
scanf("%d", &option);
if(strcmp(option, "a")==0){
printf("Welcome to Athlete Data Page\n");
}
else if(strcmp(option,"b")==0){
printf("Determine Distance to Reach World Record\n");
}else if(strcmp(option, "c")==0){
printf("Athlete Management Report");
}else if (strcmp(option, "d")==0){
printf("Exit Menu");
printf("Press Y for yes and N for no");
}
else{
printf("Incorrect code entered.");
}
return 0;
}

You are using a C-style string variable (an array of characters) char option[4];, but reading it as a decimal integer using the %d in scanf. You would want the %s option to do that.
http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm

Related

Prompt error when user enters a char instead of an expected int

I'm making a menu that lists options 1-3. The user is expected to enter an integer.
scanf("%d", &select_option)
How do I prompt error when user enters a char (for example "a", or "asd" for long strings, or a mixture like "1a2") instead of an expected int? Thanks.
Note: When the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason.
Here's my program (minimal example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
while(select_option != 4)
{
switch(select_option)
{
case 1:
printf("You like tennis! Nice! \n");
break;
case 2:
printf("You like badminton! Nice!");
break;
case 3:
printf("You like basketball! Nice!");
break;
default:
system("clear");
printf("Invalid option. Please re-enter your choice (1-4).\n");
}//end switch
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
}//end while
}//end main
You could do this:
#include <stdio.h>
int main(void) {
int v;
int ret = scanf("%d", &v);
if(ret == 1)
printf("OK, %d\n", v);
else
printf("Something went wrong!\n");
return 0;
}
where I took advantage of the return value of scanf(), and based on that value, I made an assumption. This will fail for the case of "1a2", but will succeed for "12" and "a".
However, this is a broad question and personally the way I would go for it is:
Use fgets() to read input.
Discard newline.
Convert string to integer (with strtol() for example).
Validate input.
I am assuming u are a beginner. You can use Switch Case which is used usually for creating menus and depending on the choice of the user executes the particular case.
I will show u a small example.
#include<stdio.h>
#include<conio.h>
int main()
{
int n;
printf("Select the sports u want to do\n");
printf("1.Tennis\n2.Karate\n3.Football\n");
scanf("%d",&n);
Switch(n)
{
case 1:printf("You chose Tennis\n");
break; //To prevent from all cases being executed we use
//break which helps from coming out of a loop
case 2:printf("You chose Karate\n");
break;
case 3:printf("You chose Football\n");
break;
default:printf("Please enter an appropriate number !");
//Cases which dont match with the input are handled by default !
}
}
Also to make the user enter input until he wants to exit add a while loop with a variable !
I hope this helps!

Parameters not passing correctly back to main

Source outline: User selects option either to 1. Make Bugatti; 2. Create Bugatti; or 3. Exit program. After each option is complete, the user should be returned back to the menu to select another option.
(Note: the user cannot display the car until it is created, hence the if statement in case 2)
The problem: User's inputs for createCar() function are not being returned back into main() (specifically to case 2 - Display Bugatti) and is displaying some large, odd values, instead of the user's inputs. I know it has something to do with the values not being stored into memory/called back to main().
Also, the while statements in createCar() function are completely being disregarded when I use parameters for some reason.
I would appreciate answers in code to make things easier to resolve personally if possible, thanks!
#include <stdio.h>
#include <math.h>
#define now 2017
//Function headers
void printMenu(void);
void createCar(int *speed, int *year, int *bhp, int *age);
int main(void)
{
//Variables
int userInput;
int topSpeed, yearMade, horsepower, carAge;
/***Loop program to return to menu after option is completed***/
for(;;)
{
//Print menu and get input from user
printMenu();
scanf("%i", &userInput), fflush(stdin);
//Validate input
while(userInput < 1 || userInput > 3)
{
printf("\nWrong input, please retry...\n");
scanf("%i", &userInput), fflush(stdin);
}
//Make decisions after user's choice
switch(userInput)
{
//Option 1: Create car then return to menu
case 1:
createCar(&topSpeed, &yearMade, &horsepower, &carAge);
continue;
//Option 2: Read car details (if created) then return to menu
case 2:
if(topSpeed == NULL)
{
printf("\nYou must first create a car, please retry...\n\n");
continue;
}
printf("\n----Bugatti Veyron----\n");
printf("Top Speed: %i km/h\nYear made: %i\nAge: %i years old\nHorsepower: %i bhp\n", &topSpeed, &yearMade, &horsepower, &carAge);
printf("----------------------\n");
continue;
//Option 3: Kill program
case 3:
exit(1);
}
}
return 0;
}
//Function: Display menu
void printMenu(void)
{
printf("-----------------------------------------\n");
printf("[Bob's Custom Car Creation Complex v1.0]\n");
printf("1. Create Bugatti\n2. Display Bugatti\n3. Exit\n");
printf("-----------------------------------------\n");
}
//Function: Make a car + validate inputs
void createCar(int *speed, int *year, int *bhp, int *age)
{
//Prompt user for top speed + validate input
printf("Enter the top speed of your Bugatti:");
scanf("%i", &speed), fflush(stdin);
while(speed <=0)
{
printf("You cannot have a top speed of nothing silly :-D\nPlease retry...\n");
scanf("%i", &speed), fflush(stdin);
}
//Prompt user for year mate + validate input
printf("What year is your Bugatti produced?:");
scanf("%i", &year), fflush(stdin);
while(year <=0)
{
printf("You cannot own a Bugatti that is from the future laddy!!\nPlease retry...\n");
scanf("%i", &year), fflush(stdin);
}
//Calculate age of car
age = now - year;
//Prompt user for horsepower + validate input
printf("How much horsepower does your Bugatti have?:");
scanf("%i", &bhp), fflush(stdin);
while(bhp <=0)
{
printf("A Bugatti with no engine... doesn't sound too promising :-O\nPlease retry...\n");
scanf("%i", &bhp), fflush(stdin);
}
}
You have to dereference the age and year pointer to get/set its value.
//Calculate age of car
*age = now - *year;
You have to remove the '&' at the scanf() in createVar, because speed, year and bhp are already pointers to int.
Enabling compiler warnings and resolving them would avoid you troubles!

Present error messages for invalid data entry

This is my first Project (kind of a text based game). How do I present error messages when text is entered in an area where numbers are prompted and vice versa. Or possibly the ability to reject improper input altogether.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char Name[20];
char q1;
int q2[2],q3[2];
float qT[3];
for(q1='n';q1!='y';)
{
printf("What is your name?\n");
gets(Name);
printf("You have entered: ");
puts(Name);
printf("Is this okay? [y/n]\n");
scanf("%s",&q1);
if(q1!='y'&&q1!='n')
printf("User error: '%c' not recognized.\nPlease enter 'y' to continue or 'n' to edit your name\n",&q1);
if(q1!='y'&&q1!='n')
scanf("%s",&q1);
}
printf("Okay, %s.",Name);
printf(" Out of the three choices which would you like to do most?\n1. Start a garden.\n2. Build a house.\n3. Travel to somewhere you've never been.\n");
scanf("%d",q2);
for (;q2[0]>3||q2[0]<1;)
{
printf("User error: '%c' not recognized.\nPlease enter one of the options given.",q2);
scanf("%d",q2);
}
if(q2[0]==1)
printf("What would you plant in your garden?\n1. Flowers\n2. Vegetables\n3. Fruit and Berries\n");
else
if(q2[0]==2)
printf("Where would you build your house?\n1. In the Mountains\n2. In the Desert\n3. By the Sea\n");
else
if(q2[0]==3)
printf("What would bring you to such a place?\n1. New faces and cultures\n2. Treasures and adventure\n3. Escape from the ordinary\n");
else
for(;q2[0]>3||q2[0]<1;)
{
printf("User error: '%c' not recognized.\nPlease enter one of the options given.",&q2);
scanf("%d",q3);
}
scanf("%d",q3);
qT[0]=(q2[0]*12)/q3[0];
printf("%f",qT[0]);
return 0;
}

Menu type program

I have an assignment to write a program for supporting an art gallery in C. It has to be menu based program using lists. I wrote the first function of the menu and I need some help writing the other three. So I have a structure of an unique code of the painting, author's name, painting's name, price, year of the painting. I have to create a function deleting a painting using the unique code, print out all the info about every painting and modifying a painting again using said code. The data has to be in a dynamic type structure using a linked list. This is the program so far.
#include <stdio.h>
void addPainting(void);
void erasePainting(void);
void printData(void);
void modifyData(void);
int main()
{
struct paintings
{
char code[20];
char name[50];
char paintingName[50];
double price;
int year;
}painting[100];
int choice;
do
{
printf("Menu\n");
printf("To add a painting press 1.\n");
printf("To erase a painting press 2.\n");
printf("To print data for all paintings by authors alphabetically press 3.\n");
printf ("To modify data for a painting press 4.\n");
printf("To exit the program press 5.\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
addPainting();
break;
}
case 2:
{
erasePainting();
break;
}
case 3:
{
printData();
break;
}
case 4:
{
modifyData();
break;
}
default: printf ("Wrong choice. Try again\n");
break;
}
}while (choice !=5);
void addPainting()
{
FILE *fp;
struct paintings painting;
printf("Enter code:");
scanf("%s", &painting.code);
printf("Enter the name of the author:");
scanf("%s", &painting.name);
printf("Enter the name of the painting:");
scanf("%s", &painting.paintingName);
printf("Enter price:");
scanf("%lf", &painting.price);
printf("Enter the year of creation:");
scanf("%d", &painting.year);
if ((fp=fopen("paintings","wb"))==NULL)
exit(1);
if ((fwrite (&painting,sizeof(painting),1,fp)!=1))
exit(2);
fclose(fp);
}
}
First problem: You are missing the closing brace ( } ) for the main() function. (but I am sure you knew that)
The reason for the struct size error is that you are attempting to create an instance of struct painting in the void addPainting() function, when it was created with local scope in the main function, and therefore it is not visible to the function. Create struct painting with global scope if you want to use it this way:
This will build (and run) but only for the functions defined, the others are commented out. There are other problems you will have to work out, or ask about.
EDITED to fix scanf() statements, show use of fopen()/fclose(), create and write strings using sprintf()/fputs()...
void addPainting(void);
//void erasePainting(void);
//void printData(void);
//void modifyData(void);
typedef struct //created with global scope, visible to all functions
{
char code[20];
char name[50];
char paintingName[50];
double price;
int year;
}PAINTING;
PAINTING painting[100];//array of instance of PAINTING
#define PATH "C:\\play\\painting.txt" //edit to your need
int main()
{
int choice;
do
{
printf("Menu\n");
printf("To add a painting press 1.\n");
printf("To erase a painting press 2.\n");
printf("To print data for all paintings by authors alphabetically press 3.\n");
printf ("To modify data for a painting press 4.\n");
printf("To exit the program press 5.\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
addPainting();
break;
}
case 2:
{
//erasePainting();
break;
}
case 3:
{
//printData();
break;
}
case 4:
{
//modifyData();
break;
}
default: printf ("Wrong choice. Try again\n");
break;
}
}while (choice !=5);
}
void addPainting(void)
{
FILE *fp;
char stringToWrite[80];
//Note: this function could be prototyped with an int argument
// to be used as an index for the array arguments of your
// structure. Currently, the indexes are hard-coded to 0,
printf("Enter code:");
//scanf("%s", &painting[0].code);
scanf("%s", painting[0].code); //& not needed for char array (char *) et. al.
printf("Enter the name of the author:");
scanf("%s", painting[0].name);
printf("Enter the name of the painting:");
scanf("%s", painting[0].paintingName);
printf("Enter price:");
scanf("%lf", &painting[0].price);
printf("Enter the year of creation:");
scanf("%d", &painting[0].year);
fp = fopen (PATH, "a");//open for create/append text file (not write binary, "wb")
if(fp)
{
sprintf(stringToWrite, "Painting Code is: %s\n", painting[0].code);
fputs(stringToWrite, fp);
// do others same way...
//...
fclose(fp);
}
}

if statement using char string - wont recognize string [duplicate]

This question already has answers here:
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 8 years ago.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main()
{
bool flag= true;
int menu_option;
char first_band [16], second_band [16], third_band [16], fourth_band [16], green[16];
while (flag)
{
printf("Please choose an option:\n");
printf("To run the program, enter 1.\n");
printf("For help, enter 2.\n");
printf("To exit, enter 3.\n");
scanf("%i", &menu_option);
switch (menu_option)
{
case 1:
printf("Please enter the colour of the first band on the resistor:\n");
scanf(" %s", first_band);
printf("Please enter the colour of the second band on the resistor:\n");
scanf(" %s", second_band);
printf("Please enter the colour of the third band on the resistor:\n");
scanf(" %s", third_band);
printf("Please enter the colour to fourth band ont he resistor. If there is no fourth band, enter 'null'.\n");
scanf(" %s", fourth_band);
flag=false;
break;
case 2:
flag=true;
printf("program instructions");
break;
case 3:
flag=false;
return 0;
break;
default:
flag=true;
printf("Invalid command.\n");
break;
}
}
printf("%s", first_band);
if (first_band == "green")
printf("the first band is %c\n", first_band);
return (0);
}
So i can't get the last "if" statement to print "the first band is %s". the print statement right above it is to see if the program is even reading the user input...which it seems to be. It just won't seem to recognize the word and execute the if statement. I feel like my syntax is wrong when dealing with the char strings, which is causing this problem, but I'm new to this so a helping hand would be much appreciated.
You have to use strcmp() instead.
if (strcmp(first_band, "green") == 0)
printf("the first band is %c\n", first_band);

Resources