Scott Mcgonigle
Scott Mcgonigle

Reputation: 11

If statement runs through whether conditions are met or not

My if statement runs through as if the conditions have been met even when they haven't. I have tried moving bits of code about and even rewriting the if statement differently but it has not changed the outcome. Does anyone know what I'm doing wrong?

#include <iostream>
#include <string>
using namespace std;

double num, num2, num3, num4, num5, num6, sum;
char input;
bool continueBool = true;
string bob;

void math()
{


    cout << "Please enter your first number" << endl;
    cin >> num;

    cout << "Please enter your second number?" << endl;
    cin >> num2;

    cout << "Please enter your third number?" << endl;
    cin >> num3;

    cout << "Please enter your fourth number" << endl;
    cin >> num4;

    cout << "Please enter your fith number?" << endl;
    cin >> num5;

    cout << "Please enter your sixth number?" << endl;
    cin >> num6;

    sum = num + num2 + num3 + num4 + num5 + num6;


}

void ifStatement() {

    if (bob == "no", "No", "NO", "nO") {

        continueBool = false;

        cout << "Good bye!" << endl;

    }
}


int main()
{
    while (continueBool = true) {


        math();

        cout << "The sum of your numbers is: " << sum << endl;

        cout << "Would you like to add any more numbers together?" << endl;

        cin >> bob;

        ifStatement();

        return 0;


    }



}

Upvotes: 0

Views: 83

Answers (4)

Mikel F
Mikel F

Reputation: 3656

Your loop problem can be explained:

while (continueBool = true)

should read

while (continueBool == true).

As your code currently stands, you are setting it to true instead of checking for a value, so it will never exit.

Upvotes: 0

Meercat9
Meercat9

Reputation: 1

This is a bit of a side note to your question, but in this context, you may want to consider converting the answer to lowercase (or uppercase) before comparing it.

That way, you can just use if (tolower(bob) == "no")


Here's an example of how to do use the tolower function

http://www.cplusplus.com/reference/cctype/tolower/

/* tolower example */
#include <stdio.h>
#include <ctype.h>
int main ()
{
  int i=0;
  char str[]="Test String.\n";
  char c;
  while (str[i])
  {
    c=str[i];
    putchar (tolower(c));
    i++;
  }
  return 0;
}

Upvotes: 0

tdao
tdao

Reputation: 17678

This is really bogus

if (bob == "no", "No", "NO", "nO")

You need to break it out with logical OR instead

if (bob == "no" || bob == "No" || bob == "NO" || bob == "nO")

As it stand, this if (bob == "no", "No", "NO", "nO") would be equivalent to if("nO") as the effect of the comma operator.

Upvotes: 2

druckermanly
druckermanly

Reputation: 2741

bob == "no", "No", "NO", "nO"

is not doing what you think it is doing. You mean to do:

bob == "no" ||
bob == "No" ||
bob == "NO" ||
bob == "nO"

Upvotes: 0

Related Questions