Unexpected output using if-else control structure - c++

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?

Related

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.

issue with program loops and if statements

I'm writing a program that tells a user when they enter a negative or positive and even or odd number
then the program ask a question, " Would you like to enter another number? y(es) or n(o)
I need to account for the user entering in something else besides 'y' and 'n'
and I need to account for if the user does not enter an integer. Last if the user selects yes, the program will need to go through the loop process of determining if they enter an integer and if its (positive or negative and odd or even)
int value;
char choice;
cout << "Please enter a number" << endl;
cin >> value;
while (!(cin >> value)) {
cin.clear();
cin.ignore(999, '\n');
cout << "Invalid data type! Please enter 'value' again" << endl;
}
if (value > 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is positive" << endl;
}
else if (value < 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is negative" << endl;
}
else if (value > 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is postive" << endl;
}
else if (value < 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is negative" << endl;
}
cout << "Would you like to try another number? Say y(es) or n(o)" << endl;
cin >> choice;
while (choice != 'y' &&choice != 'n') {
cin.clear();
cin.ignore(999, '\n');
cout << "Invalid response! Please enter 'choice' again" << endl;
}
do {
if (choice == 'y') {
cout << "Please enter a number" << endl;
cin >> value;
if (!(cin >> value)) {
cin.clear();
cin.ignore(999, '\n');
cout << "Invalid data type! Please enter 'value' again" << endl;
if (value > 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is positive" << endl;
}
else if (value < 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is negative" << endl;
}
else if (value > 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is postive" << endl;
}
else if (value < 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is negative" << endl;
}
cout << "Would you like to try another number? Say y(es) or n(o)" << endl;
cin >> choice;
}
}
} while (choice == 'n');
cout << "Thank you for using my program. Goodbye!" << endl;
return 0;
}
It would take nested do-while loops to check all your conditions.
Here I am using cin.fail(). cin.fail() detects whether the value entered fits the value defined in the variable.
int value;
char choice;
do{
cout << "Please enter a number" << endl;
cin >> value;
if(cin.fail()) // check if input is int
{
cout<<"Not an int";
choice = 'y';
}
else
{
if (value > 0 && value % 2 == 0)
{
cout << value << " is even" << endl;
cout << value << " is positive" << endl;
}
else if (value < 0 && value % 2 != 0)
{
cout << value << " is odd" << endl;
cout << value << " is negative" << endl;
}
else if (value > 0 && value % 2 != 0)
{
cout << value << " is odd" << endl;
cout << value << " is postive" << endl;
}
else if (value < 0 && value % 2 == 0)
{
cout << value << " is even" << endl;
cout << value << " is negative" << endl;
}
do{
cout << "Would you like to try another number? Say y(es) or n(o)" << endl;
cin >> choice;
}while(choice != 'y' || choice != 'n');
}
}while (choice == 'n');
Also you should read this: Checking input value is an integer

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.

C++ Van loading program

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.

C++ my program reads backspace as a character

I am working with a c++ program, but I am stuck with annoying bug. The bug is that when i type the password, it counts backspace as a character so can I fix it? Here is the code.
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
string password, username, lon, nu, np;
char c;
int StarNum = 0, humanproof;
cout << "Do you wanna create a user or login?";
cout << "\nLogin" << endl;
cout << "New" << endl;
cin >> lon;
if(lon=="login"){
goto login;
}
if(lon=="new"){
goto newa;
}
login:
cout << "Username: ";
cin >> username;
lol:
cout << "Password: ";
while (c != 13)
{
c = (char)getch();
if(c == 13) break;
StarNum++;
password += c;
cout << "*";
if (c == 127 || c == 8){
//go here to fix the problem
}
password = "";
goto lol;
}
}
if(username == "user" && password == "pass" || username == nu && password == np){
cout << "\nYou are logged in.";
goto options;
} else {
cout << "\nusername or password is wrong" << endl;
return 0;
}
return 0;
newa:
cout << "Username:";
cin >> nu;
cout << "password:";
cin >> np;
cout << "Type the number fourhoundred and twentie three too proof you are a human: ";
cin >> humanproof;
if(humanproof == 423){
cout << "The username is " << nu << endl;
for(int no = 0; no <= 100; no++){
cout << endl;
}
goto login;
return 0;
}
if(humanproof!=423){
cout << "wrong answer!";
return 0;
}
options:
int op;
cout << "\nwhat do you want to do?" << endl;
cout << "1. Calculator" << endl;
cout << "2. About"<< endl;
cout << "3. Just for fun" << endl;
cout << "4. Exit" << endl;
cin >> op;
if(op==1){
goto calculator;
}
if(op==2){
goto info;
}
if(op==3){
goto fun;
}
if(op==4){
return 0;
}
else{
cout << "you entered a invalid number. " << endl;
return 0;
}
calculator:
double n1, n2, sum;
int opa;
cout << "Choose a operation" << endl;
cout << "1. Addition/+" << endl;
cout << "2. Subscraction/-" << endl;
cout << "3. Multiplication/x" << endl;
cout << "4. Divsion/ /" << endl;
cin >> opa;
if(opa == 1){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 + n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 2){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 - n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 3){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 * n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 4){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 / n2;
cout << "the sum is " << sum;
return 0;
}
if(opa > 4){
cout << "You entered a invalid number";
goto calculator;
}
info:
cout << "Created by Bergur 2013";
return 0;
fun:
cout << "You want an eyepad(ipad)?";
}
Your code already checks:
while (c != 13)
And prevent newline from being handled, do similar to what you need with the backspace character, whose number is 8
To fix your issue, before:
StarNum++;
Add:
if (c == 8 && StarNum > 0) {
StarNum--;
if (password.size () > 0)
password.resize (password.size () - 1);
continue;
}
Please format your code. Also, try to provide a minimal code which reproduce the problem, not the whole code.
Unrelated to your problem
Try not to use goto.
Do not use ASCII values, but use the char literals instead, i.e. use '\n' instead of 13.
Also, you can simply add an iother condition inside your while:
while (c != '\n' && c != ' ')