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;
}
Related
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!
I'm brand new to C and I'm trying to figure out what in the world is causing this. Another similar question said that I had to download another library but that hasn't fixed the issue. So, hopefully someone can spot my problem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum Subject {SER=0, EGR=1, CSE=2, EEE=3} subject;
struct Course {
enum Subject subject;
int number;
char teacher[1024];
int hours;
} *course;
//place to store course information
struct Course* CourseCollection = NULL;
//number of courses in the collection. also the index of the next empty element.
int courseCount = 0;
void branching(char option);
void course_insert(struct Course course);
int main() {
char input_buffer;
printf("Welcome to ASU Class Schedule\n");
//menu and input loop
do {
printf("\nMenu Options\n");
printf("------------------------------------------------------\n");
printf("a: Add a class\n");
printf("d: Drop a class\n");
printf("s: Show your classes\n");
printf("q: Quit\n");
printf("\nTotal Credits: %d\n\n", courseCount);
printf("Please enter a choice ---> ");
scanf(" %c", &input_buffer);
branching(input_buffer);
} while (input_buffer != 'q');
return 0;
}
//takes a character representing an inputs menu choice and calls the appropriate
//function to fulfill that choice. display an error message if the character is
//not recognized.
void branching(char option) {
int prefix, courseNum, credits;
char instructor;
struct Course course1;
switch(option) {
case 'a' :
printf("Adding a class");
printf("\nWhat is the subject (SER=0, EGR=1, CSE=2, EEE=3)? ");
scanf(" %d", &prefix);
course1.subject = prefix;
printf("\nWhat is the course number (e.g. 334)? ");
scanf(" %d", &courseNum);
course1.number = courseNum;
printf("\nHow many credits is the class? ");
scanf(" %d", &credits);
course1.hours = credits;
printf("\nWhat is the name of the teacher? ");
scanf(" %s", &instructor);
strlcpy(course1.teacher, instructor, 1024);
printf(" %s %d", course1.subject, course1.number);
courseCount++;
course_insert(course1);
break;
case 'd' :
// TODO
break;
case 's' :
// TODO
break;
case 'q' :
printf("Goodbye ");
break;
default :
printf("Error: Invalid Input. Please Try Again. ");
break;
}
void course_insert(struct Course course) {
CourseCollection = malloc(sizeof(course)*courseCount);
}
}
The problem is a syntactical bug; the function definition for course_insert() is inside the curly braces of the function definition of branching(). You need to fix the curly braces:
void branching (char option)
{
// Code for function
}
void course_insert(struct Course course)
{
CourseCollection = malloc(sizeof(course)*courseCount);
}
I am NEW to the c programming language and currently writing a small code for my final project. The code below is a draft of the final product. Basically its a grading system where files will be incorporated later. But for now, I am just trying to test the program to see where I stand. I am receiving an error.
[Error] ld returned 1 exit status. This is the code.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main ()
{
int use;
int key;
int pass,i;
int a;
do
{
menu (a);
switch(a)
{
case 1:
for(i=1;i<5;i++)
{
printf("Please enter your username and password \n");
scanf("%d",&use);
printf("");
scanf("%d",& pass);
if (use ==711 && pass ==90210)
{
printf("\n Student Name");
printf("\n student subjects/student letter grade");
printf("\n");
printf("\n");
printf("\n");
printf("\t\t student GPA");
printf("\n Please enter any key to exit");
scanf("%d",& key);
break;
}
}
case 2:
for(i=1;i<5;i++)
{
printf("Please enter your username and password \n");
scanf("%d",&use);
printf("");
scanf("%d",& pass);
if (use ==911 && pass ==90211)
{
printf("Would you like to update student grades?");
}
break;
}
case 3:
for(i=1;i<5;i++)
{
printf("Please enter your username and password \n");
scanf("%d",&use);
printf("");
scanf("%d",& pass);
if (use ==1011 && pass ==90215)
{
printf("\n below the amount of users that accessed the system today");
printf("\n **********");
printf("\n");
}
break;
default:
printf("Please try agagin");
}
}
} while (a!=4);
return 0;
getch();
}
int menu(a)
{
printf("\t Welcome to Ski Academy Portal");
printf("\n 1. Student \t");
printf("\n 2. Staff \t");
printf("\n 3. Administrative \t");
printf("\n 4. Exit \t");
printf("\n Please enter your number choice \n");
scanf("%d",&a);
return 0;
}
Your error appears to be related to the fact that menu has no declaration before you attempt to use it. The warning:
warning: implicit declaration of function ‘menu’
Is fairly self-explanatory. Depending on the compiler, that will flow through to the link stage and generate the ld returns -1 error because the linker cannot find the definition of a function named menu.
Create a declaration of menu at the top of your code after the includes. e.g.
...
#include<string.h>
int menu(a);
int main (void) {
...
or preferably:
int menu (int a);
Also note 'i' and 'a' are used uninitialized in main(). Make sure you provide a value for them before you attempt to use them.
Compiling with -Wall -Wextra (e.g. warning enabled) will tell you all of this in a concise fashion.
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
The following code is a project I'm working on and after entering the details as in name and email it won't go to the next part of the code which is printing the price and then go to the next function. What did I do wrong??
Also, what can I do so that a customer can enter their details with spacing?
Thanks in advance.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int option,card_num,csc,phone_number;
char name,address,e_mail,registration;
void membership();
void payment();
int main()
{
membership();
return 0;
}
void membership()
{
printf("\tTHE CRUMP'S MEMBERSHIP");
printf("\n\n This membership ...");
printf("\n\n REGISTRATION [CONTRACTOR(A)/CORPORATION(B)]=");
scanf("%c",®istration);
switch (registration)
{
case 'A':
printf("\n\nEnter details without any spacing.");
printf("\nNAME:");
scanf("%s",&name);
printf("\nADDRESS:");
scanf("%s",&address);
printf("\nPHONE NUMBER:");
scanf("%d",&phone_number);
printf("\nE-MAIL:");
scanf("%s",&e_mail);
break;
case 'B':
printf("Enter details without any spacing.");
printf("\nNAME OF CORPORATION:");
scanf("%s",&name);
printf("\nADDRESS OF CORPORATION:");
scanf("%s",&address);
printf("\nPHONE NUMBER OF CORPORATION:");
scanf("%d",&phone_number);
printf("\nE-MAIL OF CORPORATION:");
scanf("%s",&e_mail);
break;
}
if (registration=='A')
printf("\n THE REGISTRATION FEE = |RM 50/MONTH |\t| RM 500/YEAR|");
else if (registration=='B')
printf("\n THE REGISTRATION FEE = |RM 200/MONTH |\t| RM 2200/YEAR|");
}
void payment()
{
printf("\n\nChoose method of payment: ");
printf("\n\t 1- Money Transfer \n\t 2-Debit Card\n");
scanf("%d",&option);
if (option==1)
{
printf("\nYou have chosen Money Transfer.");
printf("\nYou can transfer your money at our bank account --> 4365 4200 1471");
printf ("\n your membership will be confirmed when we have received the payment");
printf("\n************************************************************");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n your transaction completed...\n\n Enjoy your membership discount.");
}
else if (option==2)
{
printf("\nYou have chosen Credit/Debit card.");
printf("\n Please enter your Credit/Debit card number:");
scanf("%d",&card_num);
printf("\n Please enter CSC code:");
scanf("%d",&csc);
printf("\nYour membership will be confirmed when we have received the payment");
printf("\n*********************************************************\n\n");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n Your transaction is completed...\n\n Enjoy your membership discount.");
}
}
You are trying to read strings into char variables:
char name,address,e_mail,registration;
//...
scanf("%s",&name);
char only holds one character, not a string. If you want to read a string use an character array:
char name[100];
//...
and pass it to scanf like this:
scanf("%s",name);
because the array already decays to a pointer and taking the address is unnecessary.
Note that this requires you to set a limit for the name length. For example I choose 100-1 = 99 characters as limit. If the input is longer, undefined behaviour occurs, which is what you are experiencing right now.
Also note that you never call payment, so this will never be executed. If you want it to be executed after membership, then you need to call it:
int main()
{
membership();
payment();
return 0;
}
Your program has no call to payment() function thats why the program flow is not complete.