C++ Van loading program - c++

I am stuck.
I have been given this problem: http://i.imgur.com/1U8PjY4.png?1
The code I've written so far is this:
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
char cIn;
char full;
int capacity = 750;
int numVans = 1;
float heaviestVan = 0;
float payload = 0;
float parcelWeight;
bool emptyBelt = false;
int main()
{
bool end = false;
while(!end)
{
start:
cout << string(25, '\n');
cout << endl << "Pauls Premier Parcels (PPP)" << endl << endl;
cout << "Van being loaded is number: " << numVans << endl << endl;
cout << "The payload of van " << numVans << " is currently " << payload << " / 750kg" << endl << endl;
cout << "Is the belt full? ('Y' or 'N'): ";
cin >> full;
if (full == 'Y' || 'y')
{
while (!emptyBelt)
{
cout << endl << endl << "Please enter the weight of the next parcel: ";
cin >> parcelWeight;
if (parcelWeight > 120)
{
cout << "The maximum parcel weight is 120kg, please weigh a different parcel: ";
cin >> parcelWeight;
}
if (payload + parcelWeight <= capacity)
{
payload = payload + parcelWeight;
cout << endl << "The parcel has been loaded onto the van" << endl << endl;
goto start;
}
else
{
cout << endl << "The current van has reached capacity and is being dispatched" << endl;
//numVans = numVans + 1;
if(payload > heaviestVan)
{
heaviestVan = payload;
}
payload = 0;
cout << endl << endl << endl << "Vans dispatched: " << numVans;
cout << endl << endl << "Weight of heaviest van: " << heaviestVan;
}
}
}
}
return 0;
}
I need to implement a statement asking the user to place parcels on the belt if the belt is empty, right now It just continues running the program.
Also the user could enter anything besides Y or y and the program would still run.

Try rewriting
if (full == 'Y' || 'y')
to
if ((full == 'Y') || (full == 'y'))
Some explanation:
if (full == 'Y' || 'y')
is the same as
if ((full == 'Y') || ('y'))
which is the same as
if ((full == 'Y') || true)
which is the same as
if (true)
regardsless of the value of the variable full.

Related

Nested IF Statement C++ Syntax

Is my syntax correct for this nested if statement?
I am trying to run through all values. But it does not seem to provide any outputs is all values are not equal to 1.
I am using Xcode so some of the code may differ than in VS.
#include <iostream>
using namespace std;
int main() {
int haveMoney, haveTime, amHungry, restaurantOpen, haveTransportation;
cout << "Yes = 1, 2 = No" << endl << endl;
cout << "Do I have money?" << endl;
cin >> haveMoney;
cout << "Do I have time?" << endl;
cin >> haveTime;
cout << "Am I hungry?" << endl;
cin >> amHungry;
cout << "Are they open?" << endl;
cin >> restaurantOpen;
cout << "Do I have transportation?"<< endl;
cin >> haveTransportation;
if ((haveMoney == 1) && (haveTime == 1) && (amHungry == 1) && (restaurantOpen == 1) && (haveTransportation == 1)){
cout << "Enjoy your McDonalds!" << endl << endl;
if (haveMoney == 2){
cout << "You're broke, so you can't have McDonalds" << endl ;
if (haveTime == 2){
cout << "You don't have enough time to go to McDonalds!" << endl ;
if (amHungry == 2){
cout << "Why are you even thinking about McDonalds, you're not hungry!" << endl ;
if (restaurantOpen == 2){
cout << "McDonalds is closed, tough luck." << endl ;
if (haveTransportation == 2){
cout << "You have no transportation to get to McDonalds." << endl ;
}
}
}
}
}
}
return 0;
}
You need chained if-else-if statements, not nested if statements. This does what you expect. Note that I have omitted the curly braces for the if statements for ease of typing.
#include <iostream>
using namespace std;
int main() {
int haveMoney, haveTime, amHungry, restaurantOpen, haveTransportation;
cout << "Yes = 1, 2 = No" << endl << endl;
cout << "Do I have money?" << endl;
cin >> haveMoney;
cout << "Do I have time?" << endl;
cin >> haveTime;
cout << "Am I hungry?" << endl;
cin >> amHungry;
cout << "Are they open?" << endl;
cin >> restaurantOpen;
cout << "Do I have transportation?"<< endl;
cin >> haveTransportation;
if ((haveMoney == 1) && (haveTime == 1) && (amHungry == 1) && (restaurantOpen == 1) && (haveTransportation == 1))
cout << "Enjoy your McDonalds!" << endl << endl;
else if (haveMoney == 2)
cout << "You're broke, so you can't have McDonalds" << endl ;
else if (haveTime == 2)
cout << "You don't have enough time to go to McDonalds!" << endl ;
else if (amHungry == 2)
cout << "Why are you even thinking about McDonalds, you're not hungry!" << endl ;
else if (restaurantOpen == 2)
cout << "McDonalds is closed, tough luck." << endl ;
else if (haveTransportation == 2)
cout << "You have no transportation to get to McDonalds." << endl ;
return 0;
}

Why is failed input validation returning me to the start of my program?

Really sorry if this is a dumb question. I know it must have a super easy solution but I've been staring at this for so long I can't see it. It doesn't help that I'm really new at this either.
Long story short for some reason entering an invalid input past the first time returns me back to my menu, and sometimes also asks me to enter weight immediately after instead of allowing me to enter a menu choice. It's just all around broken and I don't know why. Thanks.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
bool loopFlag = true;
bool loopFlagTwo = true;
int choice = 0;
int time = 0;
float weightPounds = 0;
float weight = 0;
const int BIKING = 8;
const int RUNNING = 10;
const int LIFTING = 3;
const float YOGA = 2.5;
int main()
{
cout << "Welcome to my Fitness Center" << endl;
do
{
cout << "\n\t____________________________________________________________" << endl;
cout << "\n\t\t\tMy Fitness Center" << endl;
cout << "\t\t\tActivity System" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\t\t\t Main Menu\n" << endl;
cout << "\t\t\t1) Stationary Bike" << endl;
cout << "\t\t\t2) Treadmill" << endl;
cout << "\t\t\t3) Weight Lifting" << endl;
cout << "\t\t\t4) Hatha Yoga" << endl;
cout << "\t\t\t5) End" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\n\nEnter the workout that you wish to track, or end to exit:" << endl;
do
{
cin >> choice;
if (cin.fail() || choice > 5 || choice < 1)
{
cout << "Invalid choice. Please choose from option 1 through 5." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 5)
{
return 0;
}
else
{
loopFlag = false;
}
}
while (loopFlag);
do
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0)
{
cout << "Invalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
weight = weightPounds / 2.2;
cout << "\nYour weight is: \n" << fixed << setprecision(1) << weight << " kilograms." << endl;
if (choice == 1)
{
do
{
cout << "For how many minutes did you do this activity? " << endl;
cin >> time;
if (cin.fail() || time <= 0)
{
cout << "Invalid time entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
}
}
while (choice != 5);
return 0;
}
You need to set loopFlag to true before every do...while() you have, or use another flag, because after the first do...while(), loopFlag is always false.

I am getting errors in my C++ program

I am current creating a weather application that is giving me an error. It said there is something wrong with != but I am not sure what is wrong so can anyone help. It is giving me the error operand types are incompatible ("std::string *" and "const char *")(there is 4) and '!=': no conversion from 'const char *' to 'std::string *'
Thank you
C++ code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void moveTemperaturesToRight(double temperatures[], double windSpeed[], string windDirection[])
{
for (int i = 3; i > 0; i--)
{
temperatures[i] = temperatures[i - 1];
windSpeed[i] = windSpeed[i - 1];
windDirection[i] = windDirection[i - 1];
}
}
int main()
{
string name;
int choice;
int numOfReadings = 0;
double temperatures[4], windSpeeds[4];
string windDirections[4];
bool initialized = false;
string str;
//Have the user provide a name for the weather station upon entry.
cout << "Enter the name of weather station: ";
getline(cin, name);
//Control loop to perform various actions.
while (true)
{
cout << "1. Input a complete weather reading." << endl;
cout << "2. Print the current weather." << endl;
cout << "3. Print the weather history (from most recent to oldest)." << endl;
cout << "4. Exit the program." << endl;
cout << "Enter your choice: ";
cin >> str;
if (str.length() != 1 || str < "1" || str > "4")
choice = 0;
else
choice = atoi(str.c_str());
//Switch based on choice.
switch (choice)
{
case 1: moveTemperaturesToRight(temperatures, windSpeeds, windDirections);
do {
cout << "Enter the temperature (a value >=0):";
cin >> temperatures[0];
} while (temperatures < 0);
//get correct wind speed
do
{
cout << "Enter the wind speed (a value >=0):";
cin >> windSpeeds[0];
} while (windSpeeds < 0);
//get correct wind direction
do
{
cout << "Enter the wind direction (North,South,East or West):";
cin >> windDirections[0];
} while (windDirections != "North" && windDirections != "South" && windDirections != "East" && windDirections != "West");
initialized = true;
if(initialized)
numOfReadings++;
if (numOfReadings > 4)
numOfReadings = 4;
break;
case 3: //Print the current weather, if valid weather is entered.
for (int i = 0; i < numOfReadings; i++)
{
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[i] << endl;
cout << "Wind speed: " << windSpeeds[i] << endl;
cout << "Wind direction: " << windDirections[i] << endl << endl;
}
if (numOfReadings == 0)
cout << "Please enter the details before asking to print." << endl;
break;
case 2: if (numOfReadings == 0)
{
cout << "Please enter the details before asking to print." << endl;
break;
}
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[0] << endl;
cout << "Wind speed: " << windSpeeds[0] << endl;
cout << "Wind direction: " << windDirections[0] << endl << endl;
break;
case 4: return 0; //Stops execution.
default: cout << "Invalid choice. Please follow the menu." << endl;
}
}
}
You need to compare an element of windDirections with the literal.
Did you mean windDirections[0] != "North" &c.?
Currently you're attempting to compare an array of std::strings, and so the compiler issues a diagnostic. It does its best in decaying the array to a pointer to std::string (hence the specific error), but then gives up.

Unexpected output using if-else control structure

When providing the program shown below the input -1.3 and -1.1 for the low and high values, respectively, it prints the error message "Error: high gallon value must be larger than or equal to the low gallon value.". However, the test for this error is if(lowGallon > highGallon), which in this given case it clearly is not. What is the explanation for this output error?
The specific section where this input validation is located is under the section with the comment //checking for numerical input errors.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double lowGallon,
highGallon,
literConvert;
const int INCREMENTER = 1;
char charVal;
bool quitting = false,
lowIsNeg = false,
highIsNeg = false,
highIsLessThanLow = false;
cout << "This program creates a gallons to liters conversion table." << endl << endl;
do {
cout << "Enter the lowest gallon value to display (q to quit): ";
cin >> lowGallon;
cout << endl;
do {
//checking for data type input errors
if (cin.fail()) {
cin.clear();
cin >> charVal;
if (charVal == 'q') {
quitting = true;
cout << endl << "Aborting; no conversion performed." << endl;
} else {
cout << "You entered an illegal character: (" << charVal << ")" << endl << endl;
cout << "Enter the lowest gallon value to display (q to quit): ";
cin >> lowGallon;
cout << endl;
}
}
} while (cin.fail() && quitting == false);
if (quitting == false) {
lowGallon = static_cast<int>(lowGallon);
cout << "Enter the highest gallon value to display (q to quit): ";
cin >> highGallon;
cout << endl;
do {
//checking for data type input errors
if (cin.fail()) {
cin.clear();
cin >> charVal;
if (charVal == 'q') {
quitting = true;
cout << endl << "Aborting; no conversion performed." << endl;
} else {
cout << "You entered an illegal character: (" << charVal << ")" << endl << endl;
cout << "Enter the highest gallon value to display (q to quit): ";
cin >> highGallon;
cout << endl;
}
}
} while (cin.fail() && quitting == false);
//checking for numerical input errors
if (quitting == false) {
cout << endl;
if(lowGallon < 0) {
cout << "Error: low gallon value must not be negative." << endl;
lowIsNeg = true;
} else {
lowIsNeg = false;
}
if(highGallon < 0) {
cout << "Error: high gallon value must not be negative." << endl;
highIsNeg = true;
} else {
highIsNeg = false;
}
if(lowGallon > highGallon) {
cout << "Error: high gallon value must be larger than or equal to the low gallon value." << endl;
highIsLessThanLow = true;
} else {
highIsLessThanLow = false;
}
}
if (quitting == false && lowIsNeg == false && highIsNeg == false && highIsLessThanLow == false) {
if (highGallon - static_cast<int>(highGallon) > 0) {
highGallon = static_cast<int>(highGallon) + 1;
}
cout << fixed << setprecision(1) << "The conversion table will be created for the gallon range" << endl;
cout << "of " << lowGallon << " to " << highGallon << " in increments of " << static_cast<double>(INCREMENTER) << endl << endl;
cout << " GALLONS TO LITERS" << endl;
cout << " CONVERSION TABLE" << endl;
cout << " Gallons " << "Liters" << endl;
cout << " ======= " << "=======" << endl;
for(int counter = lowGallon; counter <= highGallon; counter += INCREMENTER) {
cout << setw(9) << setprecision(1) << static_cast<double>(counter);
literConvert = counter * 3.785;
cout << setw(11) << setprecision(3) << literConvert << endl;
}
} else if (quitting == false) {
cout << "Please re-enter low and high gallon values correctly." << endl << endl << endl;
}
}
} while(quitting == false && (lowIsNeg == true || highIsNeg == true || highIsLessThanLow == true));
return 0;
}
In your code you do
lowGallon = static_cast<int>(lowGallon);
which truncates the lowGallon value from -1.3 to -1.0. But you never truncate highGallon value.
The rest follows. -1.0 is indeed greater than -1.1, hence the error message.
Why are you doing this? What's the point of that intermediate conversion to int?

Serendipity booksellers software program C++

this is a project I'm working on which comes from the book I'm using to learn C++ - "Starting out with C++". I'm having a problem with the cashier portion of the project at the moment. It asks the user to enter the date, quantity, isbn, title, and price of the book. Then, it asks the user if they wish to enter another book. Regardless of whether they type "y" or "n" it continues to the next part of the program. I don't really know why the for loop doesn't repeat after I type "y" to enter another book. Also, the date is coming out with garbage at the end when it is displayed, that's another thing I need to fix. Any help would be appreciated. There is definitely more problems but the main problem is in the cashier function in the first for loop. I didn't include the whole program because it's very long.
/*
* mainmenu.cpp
* Serendipity Booksellers software
*
* Created by Abraham Quilca on 9/5/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include<iostream>
#include<iomanip>
#include<cstring>
#include"mainmenu.h"
using namespace std;
char bookTitle[20][51],
isbn[20][14],
author[20][31],
publisher[20][31],
dateAdded[20][11];
int qtyOnHand[20];
double wholesale[20];
double retail[20];;
int main()
{
int choice;
do
{
cout << "\t\t Serendipity Booksellers"<< endl;
cout << "\t\t\t Main Menu" << endl << endl;
cout << "\t\t1. Cashier Module" << endl;
cout << "\t\t2. Inventory Database Module" << endl;
cout << "\t\t3. Report Module" << endl;
cout << "\t\t4. Exit" << endl << endl;
cout << "\t\tEnter your choice: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
cashier();
break;
case 2:
invmenu();
break;
case 3:
reports();
break;
case 4:
continue;
break;
default:
cout << "\t\tPlease enter a number in the range 1-4." << endl << endl;
}
}
while(choice != 4);
cout << "\t\tYou selected item 4." << endl;
return 0;
}
// Cashier function
void cashier()
{
char again;
char date[8];
int quantity[20] = {0};
char ISBN[20][20] = {0};
char title[20][40] = {0};
float price[20] = {0}, bookTotal[20] = {0}, subtotal, total, tax;
const float tax_rate = .06;
cout << "Serendipity Booksellers" << endl;
cout << " Cashier Module" << endl << endl;
for(int count = 0; count < 20; count++)
{
cout << "Date: ";
cin >> date;
cout << "Quantity of Book: ";
cin >> quantity[count];
cout << "ISBN: ";
cin >> ISBN[count];
cout << "Title: ";
cin.ignore();
cin.getline(title[count], 40);
cout << "Price: ";
cin >> price[count];
bookTotal[count] = quantity[count] * price[count];
subtotal += price[count];
cout << "Would you like to enter another book? (Y/N) ";
cin >> again;
if(again == 'N' || 'n')
count = 21; // This line will end the for loop
}
// Calculating tax and total
tax = subtotal * tax_rate;
total = subtotal + tax;
cout << "\n\nSerendipity Booksellers" << endl << endl;
cout << "Date:" << date << endl << endl;
cout << "Qty\t ISBN\t\t "
<< left << setw(40) << "Title" << "Price\t Total" << endl
<< "-------------------------------------------------------------------------------"
<< endl << endl;
for(int count = 0; count < 20; count++)
{
cout << quantity[count] << "\t " << ISBN[count] << " " << left << setw(40) << title[count]
<< setprecision(2) << fixed << "$" << setw(6) << price[count] << " $" << setw(6) << bookTotal[count]
<< endl << endl;
}
cout << "\t\t\t Subtotal" << "\t\t\t\t $" << setw(6) << subtotal << endl;
cout << "\t\t\t Tax" << "\t\t\t\t $" << setw(6) << tax<< endl;
cout << "\t\t\t Total" "\t\t\t\t $" << setw(6) << total << endl << endl;
cout << "Thank You for Shopping at Serendipity!" << endl << endl;
}
if(again == 'N' || 'n')
This doesn't do what you think it does. Look at it like this:
if((again == 'N') || ('n'))
Is again == N true OR is n true? Well n will always be true (it is a char with non-zero value) so your loop will always end immediately. What you want is:
if(again == 'N' || again == 'n')
Also, you can break out of a loop using the aptly named break keyword:
if (again == 'N' || again == 'n') {
break;
}
The problem with the loop is this line:
if(again == 'N' || 'n')
C++ doesn't know that you mean it to check again against both characters. Instead, it tries again == 'N', which fails, and then tries 'n', which - not being zero - evaluates as true.
Instead, try:
if (again == 'N' || again == 'n')
break;