issue with program loops and if statements - c++

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

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 my last else condition not executing correctly

why is it when I input anything other than int I get 0 is an even number, the plan was if the user enters something that's not an integer it should output invalid input
cout << "Enter an integer: ";
cin >> input;
if(input % 2 == 0) {
cout << input << " is an even "
"number" << endl;
}else if(input % 2 != 0) {
cout << input << " is an odd "
"number" << endl;
}else {
cout << "Invalid input!" << endl;
}
cin >> input is an operation that can fail, and if it fails the input variable does not contain a useful value. You can check whether it succeeded by converting cin to bool:
cin >> input;
if (!cin) {
cout << "Invalid input!" << endl;
} else if (input % 2 && input != 0) {
...
Or, since cin >> input returns the cin object again, this is equivalent:
if (!(cin >> input)) {
cout << "Invalid input!" << endl;
} else if (input % 2 && input != 0) {
...
Here's the code that works thanks to jtbandes
Exercise - Write a program to check whether a given number is ODD or Even
cout << "Even/Odd Program" << endl;
int input;
cout << "Enter an integer: ";
cin >> input;
if (!(cin >> input)) {
cout << "Invalid input!" << endl;
} else if(input % 2 == 0) {
cout << input << " is an even "
"number" << endl;
}else
cout << input << " is an odd "
"number" << endl;
return 0;
}

Throwing an instance of "out of range" in c++

When i build and run the code, i get the next error: "terminate called after throwing an instance of 'std::out_of_range'
what<>: vector::_M_range_check: __n <which is 0> >= this->size<> <which is 0>
I don't know how to fix this problem, I am new to coding!
What I'm trying to do is using a collection (list) of integers and allowing the user to select options from a menu to perform operations on the list.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector <int>numbers{};
int nr_to_add{};
char selection{};
double average{};
int min = numbers.at(0);
int max = numbers.at(0);
do{
cout << "P - Print numbers!" << endl;
cout << "A - Add numbers!" << endl;
cout << "M - Display mean of the numbers!" << endl;
cout << "S - Display the smallest number!" << endl;
cout << "L - Display the largest number!" << endl;
cout << "Q - Quit" << endl;
cout << "Enter your selection: ";
cin >> selection;
if(selection == 'p' || selection == 'P'){
for(int i = 0; i < numbers.size(); i++)
cout << "The numbers are: " << numbers[i];
if(numbers.empty())
cout << "[] - the list is empty! " << "\nYou should add some numbers!" << endl;
cout << "Add some numbers: ";
cin >> nr_to_add;
numbers.push_back(nr_to_add);
}else if(selection == 'a' || selection == 'A'){
cout << "Add the number you want: ";
cin >> nr_to_add;
cout << "\n" << nr_to_add << " has been added successfully!" << endl;
numbers.push_back(nr_to_add);
}else if(selection == 'm' || selection == 'M'){
if(numbers.empty())
cout << "Unable to calculate de average - no data introduced!" << endl;
if(numbers.size() != 0)
average = accumulate(numbers.begin(),numbers.end(), 0.0)/numbers.size();
cout << "The average is: " << average << endl;
}else if(selection == 's' || selection == 'S'){
if(numbers.empty())
cout << "Unable to determine the smallest number - list is empty!";
if(numbers.size() != 0)
for(int i = 0,n = 0; i <= n; i++){
if(numbers.at(i) < min)
min = numbers[i];
cout << "The smallest number is: " << min << endl;
}
}else if(selection == 'l' || selection == 'L'){
if(numbers.empty())
cout << "Unable to determine the largest number - list is empty!";
if(numbers.size() != 0)
for(int i = 0,n = 0; i <= n; i++){
if(numbers.at(i) > max)
max = numbers[i];
cout << "The largest number is: " << max << endl;
}
}else if(selection == 'q' || selection == 'Q'){
cout << "Goodbye..." << endl;
} else {
cout << "Unknown selection, please try again" << endl;
}
} while(selection != 'q' && selection != 'Q');
return 0;
}
The problem is that you are calling at(0) on an empty vector. That is what the out_of_range error is telling you. You need to move the calls into your if statements where the values are actually being used, after you perform your empty() checks.
Also, your min and max loops are coded wrong. And you don't need to use loops at all, you can use the standard std::min_element() and std::max_element() algorithms instead (you are already using the std::accumulate() algorithm).
Try something more like this:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <limits>
using namespace std;
int main()
{
vector<int> numbers{};
int nr_to_add;
char selection;
double average_nr;
int min_nr, max_nr;
do {
cout << "P - Print numbers!" << endl;
cout << "A - Add numbers!" << endl;
cout << "M - Display mean of the numbers!" << endl;
cout << "S - Display the smallest number!" << endl;
cout << "L - Display the largest number!" << endl;
cout << "Q - Quit" << endl;
cout << "Enter your selection: ";
if (!(cin >> selection)) {
selection = '\0';
cin.clear();
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (selection == 'p' || selection == 'P') {
if (numbers.empty()) {
cout << "The list is empty! " << "\nYou should add some numbers!" << endl;
} else {
cout << "The numbers are:"
for(size_t i = 0; i < numbers.size(); ++i) {
cout << " " << numbers[i];
}
cout << endl;
}
}
else if (selection == 'a' || selection == 'A') {
cout << "Add the number you want: ";
if (cin >> nr_to_add) {
numbers.push_back(nr_to_add);
cout << "\n" << nr_to_add << " has been added successfully!" << endl;
} else {
cout << "Bad input, please try again" << endl;
cin.clear();
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else if (selection == 'm' || selection == 'M'){
if (numbers.empty()) {
cout << "Unable to calculate the average - list is empty!" << endl;
} else {
average_nr = accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
cout << "The average is: " << average_nr << endl;
}
}
else if (selection == 's' || selection == 'S') {
if (numbers.empty()) {
cout << "Unable to determine the smallest number - list is empty!";
} else {
/*
min_nr = numbers[0];
for(size_t i = 1; i < numbers.size(); ++i){
if (numbers[i] < min_nr) {
min_nr = numbers[i];
}
}
*/
min_nr = *min_element(numbers.begin(), numbers.end());
cout << "The smallest number is: " << min_nr << endl;
}
}
else if (selection == 'l' || selection == 'L') {
if (numbers.empty()) {
cout << "Unable to determine the largest number - list is empty!";
} else {
/*
max_nr = numbers[0];
for(size_t i = 1; i < numbers.size(); ++i){
if (numbers[i] > max_nr) {
max_nr = numbers[i];
}
}
*/
max_nr = *max_element(numbers.begin(), numbers.end());
cout << "The largest number is: " << max_nr << endl;
}
}
else if (selection == 'q' || selection == 'Q') {
cout << "Goodbye..." << endl;
}
else {
cout << "Unknown selection, please try again" << endl;
}
}
while (selection != 'q' && selection != 'Q');
return 0;
}
Try this
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector <int>numbers{};
int nr_to_add{};
char selection{};
double average{};
int min = 0;
int max = 0;
do {
cout << "P - Print numbers!" << endl;
cout << "A - Add numbers!" << endl;
cout << "M - Display mean of the numbers!" << endl;
cout << "S - Display the smallest number!" << endl;
cout << "L - Display the largest number!" << endl;
cout << "Q - Quit" << endl;
cout << "Enter your selection: ";
cin >> selection;
if (selection == 'p' || selection == 'P') {
for (int i = 0; i < numbers.size(); i++)
cout << "The numbers are: " << numbers[i];
if (numbers.empty()) {
cout << "[] - the list is empty! " << "\nYou should add some numbers!" << endl;
cout << "Add some numbers: ";
cin >> nr_to_add;
numbers.push_back(nr_to_add);
min = nr_to_add;
max = nr_to_add;
}
}
else if (selection == 'a' || selection == 'A') {
cout << "Add the number you want: ";
cin >> nr_to_add;
cout << "\n" << nr_to_add << " has been added successfully!" << endl;
if (numbers.empty) {
min = nr_to_add;
max = nr_to_add;
}
else {
if (min > nr_to_add) min = nr_to_add;
if (max < nr_to_add) max = nr_to_add;
}
numbers.push_back(nr_to_add);
}
else if (selection == 'm' || selection == 'M') {
if (numbers.empty())
cout << "Unable to calculate de average - no data introduced!" << endl;
if (numbers.size() != 0)
average = accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
cout << "The average is: " << average << endl;
}
else if (selection == 's' || selection == 'S') {
if (numbers.empty())
cout << "Unable to determine the smallest number - list is empty!";
else
cout << "The smallest number is: " << min << endl;
}
else if (selection == 'l' || selection == 'L') {
if (numbers.empty())
cout << "Unable to determine the largest number - list is empty!";
else
cout << "The largest number is: " << max << endl;
}
else if (selection == 'q' || selection == 'Q') {
cout << "Goodbye..." << endl;
}
else {
cout << "Unknown selection, please try again" << endl;
}
} while (selection != 'q' && selection != 'Q');
return 0;

My program will loop regardless of whatever char I enter

I have been working on a very very basic calculation program in C++. It calculates the square root of a number, and also squares it if the user wants. This is what I have so far (I know it's probably rubbish code, but I'm a beginner just experimenting to see how it all works. Any suggestions greatly appreciated though):
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int number; // Global variables to be used in void functions as well as main.
int squaredNumber;
double sqrtResult;
char input;
char useAgain;
void squareNum(); // Prototypes for the void functions
void sqrtNum();
void useAgainQuery();
int main()
{
retry: // Establishing somewhere to send user if their input is invalid.
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Do you want to square a number or find the square root of a number?" << endl;
cout << "Please select 1 or 2 respectively." << endl;
cout << endl;
cin >> input;
if (input == '1')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
squareNum(); // If the input is 1, run the void to square a number.
}
else if (input == '2')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
sqrtNum(); // If the input is 2, run the void to sqrt a number.
}
else if (input != '1' || '2')
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Your selection was invalid, please enter 1 or 2." << endl;
cin.ignore().get();
goto retry; // If the input isn't either 1 or 2, send back to the start of program.
}
return 0;
}
void squareNum() // function to square the inputted number.
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Enter the number you want to square." << endl;
cin >> number;
cout << "You have chosen: " << number << endl;
cout << "Press ENTER to calculate." << endl;
cin.ignore().get();
system("cls");
squaredNumber = number * number; // Simple maths to find the square number
cout << "You have squared " << number << "." << endl;
cout << "The result was " << squaredNumber << "." << endl;
cout << "Press ENTER to continue." << endl;
cin.get();
useAgainQuery();
return;
}
void sqrtNum()
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Enter the number you would like the square root of." << endl;
cin >> number;
cout << "You have chosen: " << number << "." << endl;
cout << "Press ENTER to calculate." << endl;
cin.ignore().get();
system("cls");
sqrtResult = sqrt(number);
cout << "You have found the square root of " << number << "." << endl;
cout << "The result was: " << sqrtResult << "." << endl;
cout << "Press ENTER to continue." << endl;
cin.get();
useAgainQuery();
return;
}
void useAgainQuery()
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Would you like to make another calculation?" << endl;
cout << "Y for Yes and N for No." << endl;
cout << endl;
cin >> useAgain;
if (useAgain == 'Y' || 'y')
{
retry2: // Establishing somewhere to send user if their input is invalid.
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Do you want to square a number or find the square root of a number?" << endl;
cout << "Please select 1 or 2 respectively." << endl;
cout << endl;
cin >> input;
if (input == '1')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
squareNum(); // If the input is 1, run the void to square a number.
}
else if (input == '2')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
sqrtNum(); // If the input is 2, run the void to sqrt a number.
}
else if (input != '1' || '2')
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Your selection was invalid, please enter 1 or 2." << endl;
cin.ignore().get();
goto retry2;
}
}
else if (useAgain != 'Y' || 'y')
return;
return;
}
So yeah, when I go through and it asks "Would you like to play again", it goes through it over and over. It doesn't matter what key I press but it loops. Any help would be greatly appreciated!
Change your condition here:
if (useAgain == 'Y' || 'y')
to
if (useAgain == 'Y' || useAgain=='y')
Also, change this:
else if (useAgain != 'Y' || 'y')
{
return;
}
to this:
else if (useAgain != 'Y' && useAgain!='y')
{
return;
}
Perhaps try creating a bool variable that controls the entire main loop, like this:
#include <InsertLibrariesHere>
int main(){
bool running=true;
while(running){
//calculations here
//continue(Y/N)?
if (input == N || input == n){running = false;}
}
}
Don't use goto, use a while(1) instead.
your last if statement is wrong, it needs to be
if (input != '1' && input != '2')
You can simplify your comparisons to letters:
if (std::toupper(useAgain) == 'Y')
or
if (std::tolower(useAgain) == 'y')
You can also convert the case after you input:
cin >> useAgain;
useAgain = std::toupper(useAgain);
if (useAgain == 'Y')
There is also std::transform is you need to transform a std::string to all lower or all upper case.

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?