I'm having trouble figuring out how to go about making a program for reserving study rooms.
1. Am I going in the right direction as far as getting the user input for the menu?
2. Once the user selects an option, how can i assign their room selection a new value to appear as open or unavailable? (Pointers?)
#include <stdio.h>
int main(void)
{
int rm1 = 0;
int rm2 = 0;
int rm3 = 0;
int rm4 = 0;
int rm5 = 0;
int rm6 = 0;
int rm7 = 0;
int rm8 = 0;
int rm9 = 0;
int rm10 = 0;
int input;
while (input != 4)
{
printf("Welcome to the Study-Room-Reservation System.\n"); /* Asks for user entry */
printf("Please Select an Option.\n------------------------------------\n");
printf("1. Reserve study room.\n");
printf("2. Leave study room.\n");
printf("3. Check Availability.\n");
printf("4. Exit.\n");
scanf("%d", &input);
if (input == 1)
{
printf("Please enter room number you would like to reserve. \n");/* 1. Reserve a room */
scanf("%d" , &)
}
else if (input == 2)
{
printf("Please enter room number you would like to exit. \n"); /* 2. Exit a room */
}
else if (input == 3)
{
printf("The following rooms are available. \n"); /* 3. Show available rooms */
}
else
{
printf("Invalid Command.\n"); /* Invalid Command */
}
}
return 0;
}
instead of
int rm1 = 0;
int rm2 = 0;
int rm3 = 0;
.
.
use an array
int room[10]; //for 10 rooms
then use it in a way like,
if( room[i] == 0 )
//room vacant
else if( room[i] == 1 )
//room occupied
Related
This is the code that I have. Currently the code prints out all the seats at once. I need it to print one seat and then restart to the user prompt. it can not assign the same seat and should show first class full when there are no more seats.
int main(int argc, char** argv) {
int firstClass[] = {1, 2, 3, 4}; //first class array
int firstLen = 4; // first class length
int userInput;
int i;
//user prompt
printf("Please type 1 for First Class\n");
printf("Please type 2 for Economy\n");
printf("Please type 0 to Quit\n");
printf("\n");
scanf("%d", &userInput); // scanning for user input
if(userInput = 1){
for(i = 0; i < 4; i++){
if(i < firstLen){
printf("Class: First Seat Number: %d\n", firstClass[i]);
}
else{
printf("First Class Full. Next flight is tomorrow.");
}
}
}
}
You can track which seats are taken with a variable. Each time a user selects 1 print out the seat number for that index, and then increment the index.
You'll then wrap this in a loop (for or while) and only exit the loop when the user enters 0. Make sure you define the variable used to track the current index outside of the loop.
Something like this:
int main(void)
{
const int first_class[] = {1, 2, 3, 4};
const size_t first_class_size = sizeof(first_class) / sizeof(first_class[0]);
size_t first_class_index = 0;
int user_input = 0;
do
{
print_menu();
scanf("%d", &user_input);
if (user_input == 1)
{
if (first_class_index < first_class_size)
{
printf("Here is your ticket information:\n");
printf("Seat Number: %d, Class: First\n\n", first_class[first_class_index++]);
continue;
}
printf("No first class seats are available.\n\n");
}
} while(user_input != 0);
}
I am writing a program in C that plays the game Craps. After my first roll, when I either land the point (win) or lose, the program just ends instead of calling is_win or is_loss.
But if it calls is_win or is_loss on my first roll, everything works fine.
I'm fairly certain this has something to do with the pointer pbal. I've been getting errors in the debugger saying unable to read memory, also Exception Thrown: Read access violation. I am still fairly new to pointers so I'm assuming this is the root cause of the problem.
# include "header.h"
int print_menu(void) {
int choice = 0;
printf("\n1. Enter balance\n2. Play game\n3. Get rules\n4. End game");
printf("\nEnter which you would like to do: ");
scanf("%d", &choice);
return choice;
}
void print_rules(void) {
printf("\nFirst Roll: If your die roll adds to 7 or 11, you win.\nIf it adds to 2, 3, or 12, you immediately lose.\nIf it adds to another number, that number becomes your 'point'");
printf("\nSecond Roll: If your die roll adds to your point, you win. If it adds to 7, you lose.\nKeep rolling until you get one of these.\n\n");
}
int get_balance(balance) {
printf("\nEnter how much money you would like to add (whole dollars): ");
scanf("%d", &balance);
return balance;
}
int prompt_bet(balance) {
int bet = 0;
do {
printf("\nEnter how much you would like to bet for this game: ");
scanf("%d", &bet);
} while (bet > balance); //repeats until its false that bet>bal
return bet;
}
int roll_dice(void) {
srand((unsigned int)time(NULL));
int enter = 1;
printf("\nEnter a 0 to roll your dice: ");
scanf("%d", &enter);
int die1 = rand() % 6 + 1;
int die2 = rand() % 6 + 1;
int dice = die1 + die2;
printf("You rolled a %d and a %d, with a total of %d.\n", die1, die2, dice);
return dice;
}
int calc_first_roll(int dice, int bet, int balance, int * pbal) {
int result0 = 0;
if (dice == 7 || dice == 11) {
is_win(bet, balance, pbal);
}
else if (dice == 2 || dice == 3 || dice == 12) {
is_loss(bet, balance, pbal);
}
else {
printf("Your point is %d", dice);
int point = dice;
int done = 1;
do {
dice = roll_dice();
done = calc_other_rolls(point, dice, balance, bet, *pbal);
} while (!done);
}
return result0;
}
void is_win(int bet, int balance, int *pbal) {
/* the pointer *pbal is pointing to mainbalance. I had to pass it
through everything to get it to affect mainbal the way I wanted it to.
Think of mainbalance as the permanent memory for keeping their bets & money right,
and int balance is just a messenger that doesn't get in the way of me trying
to use a pointer on mainbalance. */
*pbal = balance + bet;
printf("You win! Your new balance is %u\n", *pbal);
}
void is_loss(int bet, int balance, int *pbal) {
*pbal = balance - bet;
printf("You lost. Your new balance is %u\n", *pbal);
}
int calc_other_rolls(int point, int dice, int balance, int bet, int *pbal) {
int done = 0;
if (dice == 7) { //Goes straight to is_l / is_w instead of looping back to calc_first
is_loss(bet, balance, *pbal);
done = 0;
}
else if (dice == point) {
is_win(bet, balance, *pbal);
done = 0;
}
else {
done = 0;
}
return done;
}
# include "header.h"
int main(void) {
int mainbalance = 0;
int choice = 0;
int *pbal = &mainbalance;
do {
choice = print_menu();
if (choice == 1) {
mainbalance = get_balance();
printf("Your balance is: %d\n", mainbalance);
choice = 8; //reprints menu
}
if (choice == 3) {
print_rules();
choice = 8;
}
if (choice == 4)
exit(1);
if (choice == 2) {
int bet = prompt_bet(mainbalance);
int dice = roll_dice();
int x = calc_first_roll(dice, bet, mainbalance, pbal);
choice = 8;
}
} while (choice > 4 || choice < 1); //keeps running code until test becomes false.
return 0;
}
In this section:
if (dice == 7) { //Goes straight to is_l / is_w instead of looping back to calc_first
is_loss(bet, balance, *pbal);
done = 0;
}
else if (dice == point) {
is_win(bet, balance, *pbal);
done = 0;
}
You're not passing is_loss and is_win the pointer, you're passing the integer value, that pbal points to. * outside of a declaration is always dereferencing.
So if calc_other_rolls gets int *pbal as an argument and you wanna pass it to another function that takes int * then you should do func(pbal) and not func(*pbal), since the second one passes the value not the pointer.
Edit: As #hollow pointed out, this gets flagged by the compiler if you enable warnings, so use them.
I'm writing this program in c where I need to re-prompt the user after an invalid input. I came to a solution only to discover that if the user enters another invalid input after the re-prompt then it continues. Can someone please show me a better solution to this? I'll show you what I had anyway:
#include <stdio.h>
#include <ctype.h>
main()
{
int ctr; // loop counter
int custID[10] = {1, 3, 5, 9, 10, // ID array
6, 4, 7, 8, 2};
double custBal[10] = {153.56, 1300.45, 684.45, 990.45, 45.54, // Balance array
1100.34, 594.45, 1340.45, 1000.00, 1134.00};
int IDsearch; // For interaction
int found = 0; // Search criteria
int inner, outer, tempID, didSwap; // For sorting the arrays
double tempBal;
char ans;
/* Firs step: Sort the arrays for efficiency */
for(outer = 0; outer < 9; outer++) // <9 and not <10, because 9 numbers will be bubble sorted
{ // the highest (10th) will remain at the bottom
didSwap = 0; // Turns one after the arrays sort
for(inner = outer; inner < 10; inner++)
{
if(custID[inner] < custID[outer]) // Ascending sort
{
tempID = custID[inner]; // Must include both,
tempBal = custBal[inner]; // otherwise the arrays wont be linked
custID[inner] = custID[outer];
custBal[inner] = custBal[outer];
custID[outer] = tempID;
custBal[outer] = tempBal;
didSwap = 1; // Flag that a swap took place
}
}
if(didSwap == 0)
{
break;
}
}
/* Second step: Interacting with the program */
printf("***Customer Balance Search***\n");
do
{
printf("Which ID number do you want to check?\n");
scanf(" %d", &IDsearch);
for(ctr = 0; ctr < 10; ctr++)
{
if(IDsearch == custID[ctr])
{
found = 1;
break;
}
}
if(found)
{
if(custBal[ctr] < 1000)
{
printf("\nCustomer #%d has a balance of $%.2f.\n", custID[ctr], custBal[ctr]);
printf("Credit is good!\n");
}
else
{
printf("\nCustomer #%d has a balance of %.2f.\n", custID[ctr], custBal[ctr]);
printf("Credit is bad! No more credit!\n");
}
}
else
{
printf("\nCustomer #%d was not found!\n", IDsearch);
printf("Please enter a correct ID number!\n\n");
continue;
}
printf("\nDo you want to search another ID number?\n");
printf("Enter (Y)es or (N)o\n");
scanf(" %c", &ans);
ans = toupper(ans);
}
while((found != 1) || (ans == 'Y' && ans != 'N'));
printf("\nExiting...\n\n");
return (0);
}
Please reset found
do {
found = 0;
// ...
at the start of the do-while loop. It is not enough to initialise it when defined.
Whenever I build my program using visual studio 2015, it says it fails, but when I rebuild immediately after, it says it succeeded. Another question is how do i store multiple inputs for SKU, price and price and then properly output it.
#include <stdio.h>
#define MAX_ITEMS 10
struct Item
{
int sku_[10];
int quantity_[10];
float price_[10];
};
int main(void)
{
int size = 0;
int input =1;
int i;
int j;
struct Item items[10];
printf("Welcome to the Shop\n");
printf("===================\n");
printf("Please select from the following options\n");
while (size <= MAX_ITEMS && input != 0)
{
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n);
printf("Select:");
scanf_s("%d", &input);
while (input < 0 || input >2 && input != 0)
{
printf("Invalid input, try again: Please select from the following);
printf("1)Display the inventory.\n2)Add to the inventory.\n0) Exit.\n");
printf("Select:");
scanf_s("%d", &input);
}
if (input == 1)
{
printf("Inventory\n");
printf("====================\n");
printf("Sku Price Quantity\n");
printf("%d", items[size].sku_);
}
else if (input == 2)
{
printf("Please input a SKU number:");
if (size >= MAX_ITEMS)
{
printf("The inventory is full");
}
else if (size < MAX_ITEMS)
{
scanf_s("%d", &items[size].sku_);
printf("Quantity:");
scanf("%d", &items[size].quantity_);
printf("Price:");
scanf("%f", &items[size].price_);
printf("The item is successfully added to the inventory.\n");
size += 1;
}
}
else if (input == 0)
{
printf("Good bye");
}
}
}
Here are errors detected in the source code:
1- As WhozCraig suggests, two printf() calls are bad terminated.
Instead of:
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n);
...
printf("Invalid input, try again: Please select from the following);
Add a text terminator:
printf("1) Display the inventory.\n2) Add to the inventory.\n0)Exit.\n");
...
printf("Invalid input, try again: Please select from the following");
2- When entering items[size].sku_, or .quantity_, or .price_, use a pointer to a value instead of a pointer to a array of value. The struct Item is malformed.
Just modify the struct Item:
struct Item
{
int sku_; // unexpected use [10];
int quantity_; // unexpected use [10];
float price_; // unexpected use [10];
};
3- When printing the inventory, use a loop and not the last index. And format all attributes of each items[i] to align with the header.
printf("Sku Price Quantity\n");
for(i=0;i<size;i++) {
printf("%6d %8d %6.2f\n", items[i].sku_,items[i].quantity_,items[i].price_);
}
I have been trying to figure out why my code isn't working properly. I know my code below is a mess (I am a rather poor C programmer thus far). Its a work in progress. Specifically
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
I find that when i run my program I might select a keyboard input of 1, meaning I am looking at my second record in my file entries.txt. The printout of vIndex however is a number much much larger, much likely the last information stored there. Running in debug however, i find that vIndex change to 1 and but prints the strange number. My entire code is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec
{
int i;
float PI;
char A;
} Record;
typedef struct
{
char fname[20];
char lname[50];
char phone[15];
} Contact;
Record * arrayAlloc(int size);
char * stringAlloc(int size);
Contact * contactAlloc();
void structAlloc();
int main(void)
{
int *ptrInt;
Record * ptrRec;
int i = 0;
char * myName;
Contact * contacts;
ptrInt = (int *)malloc(sizeof(int));
int vIndex=0;
int displayMenu();
Contact * contactAlloc();
// void searchIndex();
void searchFirst();
void searchLast();
void searchPhone();
contacts = contactAlloc();
char choice;
choice = displayMenu();
while (choice !=5)\
{
if (choice == 1)
// searchIndex();
{
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
// fgets(vIndex, 700, stdin);
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. \nPhone Number:\t%c.\n\n ", &vIndex, contacts[vIndex].fname, contacts[vIndex].lname, contacts[vIndex].phone);
}
else if (choice == 2)
searchFirst();
else if (choice == 3)
searchLast();
else if (choice == 4)
searchPhone();
choice = displayMenu();
}
printf("Thank for you using this program.\n");
return 0;
}
int displayMenu()
{
int choice = 0;
while (choice!= 1 && choice != 2 && choice != 3 && choice != 4 && choice!=5)
{
printf("\nWelcome to the phone book application. Please choose from the following options:");
printf("\n\n\t 1) Search the phone book by index. \n\t 2) Search the phone book by first name. \n\t 3) Search the phone book by last name. \n\t 4) Search the phone book by phone number. \n\t 5) Quit.\n\n");
scanf("%d", &choice);
}
return choice;
}
Contact * contactAlloc()
{
FILE * fin;
int count = 0, i = 0;
char aLine[100];
Contact * ptrContact;
fin = fopen("entries.txt", "r");
if (fin != NULL)
{
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
count++;
}
fseek(fin, 0L, SEEK_SET);
count = count / 3;
ptrContact = (Contact *) calloc(count, sizeof(Contact));
count = 0;
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
if (aLine[strlen(aLine) - 1] == '\n')
{
aLine[strlen(aLine) - 1] = '\0';
}
if (i % 3 == 0)
{
strcpy(ptrContact[count].lname, aLine);
}
else if (i % 3 == 1)
{
strcpy(ptrContact[count].fname, aLine);
}
else if (i % 3 == 2)
{
strcpy(ptrContact[count].phone, aLine);
//printf("Line %d at count %d: %s\n", i, count, aLine);
count++;
}
i++;
}
//count=count*3;
printf("%d contacts loaded.\n\n", count);
fclose(fin);
}
return ptrContact;
}
/*
void searchIndex()
{
int vIndex=0;
printf("Please enter the index of the contact you wish to view. This should be a positive integer");
scanf("%d", &vIndex);
fgetc(stdin);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. Phone Number:\t%c.\n\n ", &vIndex, &Contact[vIndex].fname, &Contact[vIndex].lname, &Contact[vIndex].phone);
}
*/
void searchFirst()
{
}
void searchLast()
{
}
void searchPhone()
{
}
You are printing the address of vIndex instead of the value:
printf("The value of vIndex is %d", &vIndex);
Change this line to the following:
printf("The value of vIndex is %d", vIndex);